具有一个参数和默认值的类模板

时间:2017-09-18 16:48:48

标签: c++ templates

我必须在这里遗漏一些明显的东西,因为这真的让我感到惊讶。

以下代码给出了错误:error: missing template arguments before ‘a’

template<int n=0>
class A {};

...
A a;
...

是否有理由为实例化为具有默认值声明的1参数的模板指定其值?

有人可以引用标准吗?

2 个答案:

答案 0 :(得分:5)

A仍然是模板类。但是你可以省略模板参数:

template<int n=0>
class A {};

int main() {
    A<> a;
  // ^^ 
    return 0;
}

请参阅live demo

我认为 1 相关的standard section就在这里

  

14.7模板实例化和专业化

     

...
  3可以为函数模板,类模板,类的成员声明显式特化   模板或成员模板。模板&lt;&gt;引入了明确的专业化声明。在   类模板的明确专门化声明,类模板的成员或类成员   模板,显式专用的类的名称应为simple-template-id。在函数模板或成员函数模板的显式特化声明中,函数的名称   或明确专门化的成员函数可以是模板ID    [实施例:

 template<class T = int> struct A {
     static int x;
 };
 template<class U> void g(U) { }
 template<> struct A<double> { }; // specialize for T == double
 template<> struct A<> { }; // specialize for T == int
 template<> void g(char) { } // specialize for U == char
 // U is deduced from the parameter type
 template<> void g<int>(int) { } // specialize for U == int
 template<> int A<char>::x = 0; // specialize for T == char
 template<class T = int> struct B {
     static int x;
 };
 template<> int B<>::x = 1; // specialize for T == int
     

- 结束示例]

1) 对不起,我找不到更好的标准引用/示例。它没有完全涵盖OP的情况,但至少表明,模板仍然需要将<>尖括号标识为模板(类或函数)。

答案 1 :(得分:3)

如果重要的是掩饰对象的性质,那么

可能的解决方法:

// the template class
template<int n=0>
class ReallyA {};

// an alias for the common case    
using A = ReallyA<0>;

A a;

这就是标准库定义std::string的方式,例如。

using string = basic_string<char>;
相关问题