在构造函数中接受某些类型
我的新类的函数本身声明类型:
class C{
public:
C();
C(T value);// specifically looking for this
T f(T value); // what the code currently does
};
链接中的代码创建一个[接受并]返回整数类型 T
的函数。我需要它根本不返回任何内容,以便它可以与构造函数一起使用
as a follow up to this question, how can the code be changed so that i can use it in the constructor of a class? im writing a new class where the input needs to be an number of some kind, but nothing else. the code, however, is like declaring the type in front of a function. since constructors dont exactly have types, i need it to not declare a type for the function itself
my new class:
class C{
public:
C();
C(T value);// specifically looking for this
T f(T value); // what the code currently does
};
the code in the link creates a function that [accepts and] returns an integer type T
. i need it to not return anything at all, so that it can be used with a constructor
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您想限制构造函数模板的类型。如果是这样,那么您可以这样做:
此构造函数模板只能接受那些
is_arithmetic::value
为true
的T
。enable_if
的实现完全相同,如 另一个答案。或者,如果您没有
type_traits
,则可以将typelist
与enable_if
一起使用。我认为这是一个更好的解决方案,因为您可以专门定义支持的类型列表。此构造函数模板只能接受那些
exists::value
为true
的T
。exists
元函数检查T
是否存在于类型列表supported_types
中,或者不存在。您可以向此类型列表添加更多类型。typelist
和exists
的实现在这里(请参阅我的解决方案):I think you want to restrict types for constructor template. If so, then you can do this:
This constructor template can accept only those
T
for whichis_arithmetic<T>::value
istrue
. The implementation ofenable_if
is exactly same, as given in the other answer.Alternatively, or if you don't have
type_traits
, then you can usetypelist
along withenable_if
. I think this is a better solution, as you can specifically define the supported typelist.This constructor template can accept only those
T
for whichexists<T,supported_types>::value
istrue
. Theexists
metafunction checks whetherT
is existing in the typelistsupported_types
or no. You can add more types to this typelist.And the implementation of
typelist
, andexists
is here (see my solution):