【问题标题】:Class template with one parameter and default value具有一个参数和默认值的类模板
【发布时间】:2018-02-27 07:05:44
【问题描述】:

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

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

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

...
A a;
...

为什么必须实例化具有 1 个使用默认值声明的参数的模板并为其指定值?

有人可以引用标准吗?

【问题讨论】:

  • 你不需要指定它:A&lt;&gt; a;
  • @W.F.有趣,你知道为什么吗?。
  • 同样你不能用没有大括号的默认参数调用函数。
  • @imreal A 不是一个类,它是一个模板。声明一个模板的变量是没有意义的——你需要一个特定的实例化&lt;&gt; 是您尝试实例化模板的编译器的线索,就像 W.F.指出() 是您尝试调用函数的线索(即使您没有传递任何参数)。

标签: c++ templates


【解决方案1】:

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

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

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

请参阅live demo


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

14.7 模板实例化和特化

...
3 可以为函数模板、类模板、类成员声明显式特化 模板或成员模板。 template 引入了显式的特化声明。在 类模板、类模板成员或类成员的显式特化声明 模板,显式特化的类的名称应为 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 的情况,但至少演示了相同的情况,即模板仍然需要将 &lt;&gt; 尖括号标识为模板(类或函数)。

【讨论】:

  • 标准的这一部分更多地是关于专门化模板。我在这里没有看到任何关于实例化模板的内容。
  • @cdhowie 我放弃了搜索。没有找到更好的引用/示例。
【解决方案2】:

如果掩盖对象的性质很重要,可能的解决方法:

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

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多