Reputation: 98746
For example, the following snippet compiles in VC++ 2010:
template<int Rows, int Columns = Rows>
struct Matrix { };
Matrix<4> m;
Note that the default argument for Columns
depends on the argument value for Rows
.
But is this standard behaviour in C++11 (or earlier) that I can rely on everywhere?
Upvotes: 5
Views: 763
Reputation: 2090
Yes. And as a matter of fact, it's how tons of STL codes work.
the std::vector
has a definition like:
template < class T, class Alloc = allocator<T> > class vector
so that you don't need to specify the allocator
each time every time. If such is invalid, we won't be able to write:
std::vector<int> data;
And you would write std::map
as:
std::map < keyType, // map::key_type
ValType, // map::mapped_type
less<keyType>, // map::key_compare
allocator<pair<const KeyType,ValType> > // map::allocator_type
> mapping;
which is far less desirable than:
std::map< keyType , ValType > mapping;
Upvotes: 4
Reputation: 6037
According to cplusplus, yes:
It is also possible to set default values or types for class template parameters. For example, if the previous class template definition had been:
template <class T=char, int N=10> class mysequence {..};
And on a more mundane note, g++ -Wall will compile it.
Upvotes: 2