Search code examples
c++templatesdefault-parameters

Is it valid to have default template arguments that are dependent on earlier arguments?


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?


Solution

  • 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;