如何将通用类方法模板参数限制为某些类型?
我已经检查了 std> std :: enable_if to有条件地编译成员功能
但是对我不起作用。我需要将类方法的t
限制为某些类型。
template<typename T = typename enable_if_t<
is_same_v<T, long> || is_same_v<T, int> || is_same_v<T, double>
|| is_same_v<T, float> || is_same_v<T, size_t>>
>
shared_ptr<Node<T>> LinkedList<T>::AddNumbers(
shared_ptr<Node<T>> p1, shared_ptr<Node<T>> p2, T carry)
{
<snip>
}
我会得到构建错误:
identifier T is undefined
我正在使用C ++ 20。任何建议和见识都将不胜感激。
我尝试概念
由@Jejo建议,但是在执行算术的行上获取以下构建错误:
error C2676: binary '/': 'T' does not define this operator or
a conversion to a type acceptable to the predefined operator
我在.cpp
文件中具有模板类声明和实现中的模板类声明。标题文件:
template <typename T> class LinkedList
{
public:
<snip>
shared_ptr<Node<T>> AddNumbers(
shared_ptr<Node<T>>, shared_ptr<Node<T>>, T carry = 0);
};
当我使用@Jejo的建议时,我会碰到
error C3855: 'LinkedList<T>': template parameter 'T' is
incompatible with the declaration
I have checked out std::enable_if to conditionally compile a member function
However it doesn't work for me. I need to restrict T
of a class method to some types.
template<typename T = typename enable_if_t<
is_same_v<T, long> || is_same_v<T, int> || is_same_v<T, double>
|| is_same_v<T, float> || is_same_v<T, size_t>>
>
shared_ptr<Node<T>> LinkedList<T>::AddNumbers(
shared_ptr<Node<T>> p1, shared_ptr<Node<T>> p2, T carry)
{
<snip>
}
I get build error:
identifier T is undefined
I am using C++20. Any advice and insight is appreciated.
I try out concepts
suggested by @JeJo, but get the following build error on the line performing arithmetics:
error C2676: binary '/': 'T' does not define this operator or
a conversion to a type acceptable to the predefined operator
I have the template class declaration in header file and implementation in .cpp
file. Header file:
template <typename T> class LinkedList
{
public:
<snip>
shared_ptr<Node<T>> AddNumbers(
shared_ptr<Node<T>>, shared_ptr<Node<T>>, T carry = 0);
};
When I use the suggestion by @JeJo, I bump into
error C3855: 'LinkedList<T>': template parameter 'T' is
incompatible with the declaration
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管其他答案说的话,但假设您使用
需要
,则成员函数并不需要(也不应该)是模板。只有在使用经典的Sfinae时,这是必要的。任何布尔条件都可以在
需要
之后拼写,但是我添加了一个简洁的概念。Despite what the other answers say, the member function doesn't need to (and shouldn't) be a template, assuming you use
requires
. That's only necessary when you use the classical SFINAE.Any boolean condition can be spelled after
requires
, but I've added a concept for brevity.