模板类方法的默认参数
Default parameters for methods of template class
是否有办法为模板类的方法提供默认参数值?例如:
template<class T>
class A
{
public:
A foo(T t);
};
我应该如何修改这给foo
的默认参数类型T
?例如:T
为int
,则默认值为-23,或者T
为char*
,则默认值为"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";
};
相关文章:
- 如何使用默认参数等选择模板专业化
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 何时提供默认参数作为模板参数
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 如何修复带有 clang 的参数'args'缺少默认参数的问题?
- 函数不接受 X 参数,函数使用默认参数
- initializer_list具有默认参数的构造函数
- C++ 带有默认参数的结构,可选择在构造函数中更改
- 为什么C++构造函数在继承中需要默认参数?
- 必须非常量别名参数及其默认参数常量
- C++ 默认参数使用其他参数
- 组合函数参数包和默认参数
- 如何定义 Vector2f 的默认参数?[SFML]
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 如何设置默认参数以防用户不输入另一个参数
- 结构 c++ 中的默认参数
- 构造函数委托与默认参数
- 默认参数和函数指针作为函数参数C++
- 如何在继承层次结构中调用具有默认参数的构造函数?