Is there a way to provide default parameter values for methods of a template class? For example I h开发者_Go百科ave 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?
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:
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);
};
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:
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";
In C++11, you could alternatively say static constexpr T value = T();
to make the template work for non-integral values, provided that T
has a default constructor that is declared constexpr
:
template <typename T> struct MyDefaults
{
static constexpr T value = T();
};
template <> struct MyDefaults<const char *>
{
static constexpr const char * value = "Hello World";
};
精彩评论