有没有办法为模板类的方法提供默认参数值?例如,我有以下内容:
template<class T>
class A
{
public:
A foo(T t);
};
我应该如何修改它以提供foo
类型的默认参数T
?例如:然后T
是int
默认值 -23,还是T
默认char*
值"something"
,等等。这甚至可能吗?
有没有办法为模板类的方法提供默认参数值?例如,我有以下内容:
template<class T>
class A
{
public:
A foo(T t);
};
我应该如何修改它以提供foo
类型的默认参数T
?例如:然后T
是int
默认值 -23,还是T
默认char*
值"something"
,等等。这甚至可能吗?
如果您希望默认参数只是默认值(通常为零),那么您可以编写A foo(T t = T())
. 否则,我建议一个特征类:
template <typename T> struct MyDefaults
{
static const T value = T();
};
template <> struct MyDefaults<int>
{
static const int value = -23;
};
template<class T>
class A
{
public:
A foo(T t = MyDefaults<T>::value);
};
我相信,在类定义中写入常量值仅适用于整数类型,因此您可能必须为所有其他类型将其写入外部:
template <> struct MyDefaults<double>
{
static const double value;
};
const double MyDefaults<double>::value = -1.5;
template <> struct MyDefaults<const char *>
{
static const char * const value;
};
const char * const MyDefaults<const char *>::value = "Hello World";
在 C++11 中,您也可以说static constexpr T value = T();
使模板适用于非整数值,前提是T
具有声明的默认构造函数constexpr
:
template <typename T> struct MyDefaults
{
static constexpr T value = T();
};
template <> struct MyDefaults<const char *>
{
static constexpr const char * value = "Hello World";
};