【发布时间】:2013-09-06 22:21:49
【问题描述】:
当我编译以下 sn-p 时,我在 clang 中得到一个编译器错误,但在 g++/MSVC 中没有:
#include <string>
template<typename T> struct Const {
explicit Const(T val) : value(val) {}
T value;
};
template<typename T> struct Var {
explicit Var(const std::string &n) : name(n) {}
std::string name;
};
template<typename L, typename R> struct Greater {
Greater(L lhs, R rhs) : left(lhs), right(rhs) {}
L left;
R right;
};
template<typename L>
Greater<L, Const<int> > operator > (L lhs, int rhs) {
return Greater<L, Const<int> >(lhs, Const<int>(rhs));
}
template<typename R>
Greater<Const<int>, R> operator > (int lhs, R rhs) {
return Greater<Const<int>, R>(Const<int>(lhs), rhs);
}
Var<double> d("d");
int main() {
d > 10;
return 0;
}
报错如下:
error: overloaded 'operator>' must have at least one parameter of
class or enumeration type
Greater<Const<int>, R> operator > (int lhs, R rhs) {
^
./val.h:31:24: note: in instantiation of function template specialization
'operator><int>' requested here
Greater<Const<int>, R> operator > (int lhs, R rhs) {
^
1 error generated.
这是关于未使用的运算符功能。相反,如果我写 10 > d 而不是 d > 10,那么我会得到关于另一个 operator > 函数的相同错误。以上在 gcc 4.4.6 和 VS2012 下编译良好。我的错误是什么?
谢谢。
【问题讨论】:
-
它也可以用 gcc 4.8.1 编译:ideone.com/wG4Yzv(C++98 模式)和ideone.com/8fwOWq(C++11 模式)。你的 clang 版本是什么?
-
@gx_ 刚试了3.1和3.2,都出现了问题。
-
@BoBTFish 谢谢(太糟糕了,没有“在线 Clang”(不再))。我想知道非常简化的示例 ideone.com/0Aooxo 吗? 编辑: 哦,等等,gcc.godbolt.org 有 clang 3.0 :) 我的简化示例导致了同样的错误。 编辑(2):再次感谢。看起来像一个编译器错误...
-
您的简化示例显示了相同的错误。删除不正确的会导致它成功。
-
或者也许它实际上不是 Clang 中的错误,但其他编译器过于宽松:p 顺便说一句,我在某处读到最好避免使用这种不受约束的模板(尤其是对于运算符重载)...找到:A Modest Proposal: Fixing ADL (revision 2)
标签: c++ templates operator-overloading clang sfinae