【发布时间】:2015-12-12 12:00:44
【问题描述】:
我不清楚编译器何时以及如何创建template 函数。所以我无法解释以下 2 个示例的行为。
示例 1。
struct C1 {
template <typename T>
void g(T t);
};
template<>
void C1::g(double x) {
cout << "Member templates. C1::g(double) " << x << endl;
}
上面的代码构建并运行。但是,如果没有 template<>,g++ 就会抱怨。
error: prototype for ‘void C1::g(double)’ does not match any in class ‘C1’
但是如果我将 g(double ) 的定义放在类中就可以了。
问题 1: 为什么成员模板方法必须在类外使用 template 专门化?
示例 2。
struct C1 {
template <typename T>
void g(T t);
void g(double x) {
cout << "C1::g(double): " << x << endl;
}
};
template<>
void C1::g(double x) {
cout << "Member templates. C1::g(double) " << x << endl;
}
C1 c;
c.g(10.5); // output: C1::g(double): 10.5
成员模板模板 void g() 未被调用。这让我想知道
问题 2。 成员模板是否曾经被专门化过?
【问题讨论】:
-
因为它是一个模板函数。不是函数重载。
-
@CoffeeandCode 谢谢。例如 1。 C1 中没有 g() 的声明。没有 template 的 g() 的定义看起来“自然”(对我来说)被解释为模板专业化。我认为编译器拥有消除定义歧义所需的一切。