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?
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 thatThas a default constructor that is declaredconstexpr: