模板类方法的默认参数

Default parameters for methods of template class

本文关键字:默认 参数 类方法      更新时间:2023-10-16

是否有办法为模板类的方法提供默认参数值?例如:

template<class T>
class A
{
public:
    A foo(T t);
};

我应该如何修改这给foo的默认参数类型T ?例如:Tint,则默认值为-23,或者Tchar*,则默认值为"something",等等。这可能吗?

如果您希望默认参数只是默认值(通常为零),那么您可以编写A foo(T t = T())。否则,我建议使用trait类:

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中,如果T有一个声明为constexpr的默认构造函数,则可以使用static constexpr T value = T();来使模板适用于非整型值:

template <typename T> struct MyDefaults
{
  static constexpr T value = T();
};
template <> struct MyDefaults<const char *>
{
  static constexpr const char * value = "Hello World";
};