首页 > 解决方案 > Inheriting a default template value

问题描述

I have multiple aliases for a class and would like those aliases to inherit the base class' default template argument. Here is a simple example of syntactically what I'm trying to achieve:

template<int f = 5>
class A {}; 

template<int T/*= 5*/>
using Test = A<T>;

int main()
{
    A<> foo;
    Test<> foo2; // error: wrong number of template arguments (0, should be 1)
}

Or do I have to resort to making the default value an explicitly accessible value?

static const int DefaultVal = 5;

template<int f = DefaultVal>
class A {}; 

template<int T= DefaultVal>
using Test = A<T>;

标签: c++templates

解决方案


您不能“继承”默认值。

另一种可能性是使用可变参数模板:

template <int ... Ts>
using Test = A<Ts...>;

这允许Test<>这样。A<>A<5>

但它“谎言”与 invalid Test<1, 2, 3, 4>


推荐阅读