我从 http://en.cppreference.com/w/cpp/language/function_template#Function_template_overloading 中获取了以下示例 和 clang (3.4) 似乎处理得很好,而 g++ (4.8.3) 给出了一个“不明确的过载”错误:
struct A {};
template<class T> struct B {
template<class R> void operator*(R&){ cout << "1" << endl; } // #1
};
template<class T, class R> void operator*(T&, R&) { cout << "2" << endl;} // #2
int main() {
A a;
B<A> b;
b * a; //prints 1
}
clang 正确打印 1(根据 cppreference 的预期),而 g++ 给出此错误:
test_templates.cpp: In function ‘int main()’:
test_templates.cpp:13:5: error: ambiguous overload for ‘operator*’ (operand types are ‘B<A>’ and ‘A’)
b * a; //prints 1
^
test_templates.cpp:13:5: note: candidates are:
test_templates.cpp:7:26: note: void B<T>::operator*(R&) [with R = A; T = A]
template<class R> void operator*(R&){ cout << "1" << endl; } // #1
^
test_templates.cpp:9:33: note: void operator*(T&, R&) [with T = B<A>; R = A]
template<class T, class R> void operator*(T&, R&) { cout << "2" << endl;} // #2
g++ 在这里真的有问题吗?
最佳答案
此示例取自 standard (这是 c++11 的草案)。
14.5.6.2 函数模板的部分排序第3段示例:
struct A { };
template<class T> struct B {
template<class R> int operator*(R&); // #1
};
template<class T, class R> int operator*(T&, R&); // #2
// The declaration of B::operator* is transformed into the equivalent of
// template<class R> int operator*(B<A>&, R&); // #1a
int main() {
A a;
B<A> b;
b * a; // calls #1a
}
因此,标准本身几乎可以说这是合法代码。我可以复制粘贴规则,但也可以单击链接并跳转到相关位置。我的观点只是为了证明这是标准定义的正确的可编译代码。
为了在我的 debian clang 3.5.0
上立即编译它的值(value),clang 3.4.2
必须使用 -std=c+ 执行+11
,g++ 4.9.1
在所有情况下都报告了歧义(我什至尝试了 1y)。
不过,我对 clang
行为感到困惑。我认为它在早期版本的 c++ 中可能有歧义,消除歧义的规则是作为 c++11 的一部分添加的,g++
没有跟上。但是 clang 3.5
即使使用 -std=c++98
也能编译它。
关于c++ - g++ 是否在函数模板重载方面表现不佳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26470503/