Is it permissible to have default template arguments that depend on previous arguments?

For example, the following snippet compiler 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 the standard behavior in C ++ 11 (or earlier) that I can rely on everywhere?

+4
source share
2 answers

Yes. And, essentially, this is how tons of STL codes work.

std::vector has a definition like:

  template < class T, class Alloc = allocator<T> > class vector 

so you don’t have to specify allocator every time every time. If this is not valid, we will not be able to write:

 std::vector<int> data; 

And you should 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 much less desirable than:

 std::map< keyType , ValType > mapping; 
+4
source

According to cplusplus , yes:

You can also set default values ​​or types for class template parameters. For example, if the previous class template definition was:

 template <class T=char, int N=10> class mysequence {..}; 

And in a more mundane note, g ++ -Wall compiles it.

+2
source

All Articles