模板类方法的默认参数
有没有办法为模板类的方法提供默认参数值?例如,我有以下内容:
template<class T>
class A
{
public:
A foo(T t);
};
我应该如何修改它以给 foo
类型为 T
的默认参数?例如:T
为 int
,则默认值为 -23,或者 T
为 char*
,则默认值“某物”
等。这可能吗?
Is there a way to provide default parameter values for methods of a template class? For example I have the following:
template<class T>
class A
{
public:
A foo(T t);
};
How should I modify this to give foo
a default parameter of type T
? For example: T
is int
then a default value of -23, or T
is char*
then default value of "something"
, etc. Is this even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望默认参数只是默认值(通常为零),那么您可以编写
A foo(T t = T())
。否则,我建议使用特征类:我相信,在类定义内部编写常量值仅适用于整数类型,因此您可能必须在所有其他类型的外部编写它:
在 C++11 中,您也可以说
static constexpr T value = T();
使模板适用于非整数值,前提是T
有一个声明为constexpr
的默认构造函数:If you want the default parameter to be just the default value (zero, usually), then you can write
A foo(T t = T())
. Otherwise, I suggest a trait class:Writing the constant value inside the class definition only works for integral types, I believe, so you may have to write it outside for all other types:
In C++11, you could alternatively say
static constexpr T value = T();
to make the template work for non-integral values, provided thatT
has a default constructor that is declaredconstexpr
: