以下代码在msvc 18.00编译正常,但在gcc 4.9.1中失败:
#include <type_traits>
template <int N> class Num { };
class Zero { };
template <int N, int M>
Num<N + M> operator+(Num<N>, Num<M>)
{
return {};
}
template <int N>
Zero operator+(Num<N>, Num<-N>)
{
return {};
}
int main()
{
Num<1> one;
Num<-1> mone;
Num<0> null;
auto a = one + one;
static_assert(std::is_same<decltype(a), Num<2>>::value, ":(");
auto b = one + mone;
static_assert(std::is_same<decltype(b), Zero>::value, ":(");
auto c = null + null;
static_assert(std::is_same<decltype(c), Zero>::value, ":(");
}
gcc的错误信息为:
ambiguous.cpp: In function 'int main()':
ambiguous.cpp:28:16: error: ambiguous overload for 'operator+' (operand types are 'Num<1>' and 'Num<-1>')
auto b = one + mone;
^
ambiguous.cpp:28:16: note: candidates are:
ambiguous.cpp:8:12: note: Num<(N + M)> operator+(Num<N>, Num<M>) [with int N = 1; int M = -1]
Num<N + M> operator+(Num<N>, Num<M>)
^
ambiguous.cpp:14:6: note: Zero operator+(Num<N>, Num<(- N)>) [with int N = 1]
Zero operator+(Num<N>, Num<-N>)
^
ambiguous.cpp:29:47: error: template argument 1 is invalid
static_assert(std::is_same<decltype(b), Zero>::value, ":(");
^
ambiguous.cpp:31:17: error: ambiguous overload for 'operator+' (operand types are 'Num<0>' and 'Num<0>')
auto c = null + null;
^
ambiguous.cpp:31:17: note: candidates are:
ambiguous.cpp:8:12: note: Num<(N + M)> operator+(Num<N>, Num<M>) [with int N = 0; int M = 0]
Num<N + M> operator+(Num<N>, Num<M>)
^
ambiguous.cpp:14:6: note: Zero operator+(Num<N>, Num<(- N)>) [with int N = 0]
Zero operator+(Num<N>, Num<-N>)
^
ambiguous.cpp:32:47: error: template argument 1 is invalid
static_assert(std::is_same<decltype(c), Zero>::value, ":(");
^
哪个编译器是正确的?
Zero
更改为using Zero = Num<0>;
来消除这种歧义。 - TartanLlama