微软编译器(Visual Studio中2017 15.2)拒绝以下代码:重载分辨率
#include <type_traits>
struct B
{
template<int n, std::enable_if_t<n == 0, int> = 0>
void f() { }
};
struct D : B
{
using B::f;
template<int n, std::enable_if_t<n == 1, int> = 0>
void f() { }
};
int main()
{
D d;
d.f<0>();
d.f<1>();
}
错误是:
error C2672: 'D::f': no matching overloaded function found
error C2783: 'void D::f(void)': could not deduce template argument for '__formal'
note: see declaration of 'D::f'
锵也拒绝它:
error: no matching member function for call to 'f'
d.f<0>();
~~^~~~
note: candidate template ignored: disabled by 'enable_if' [with n = 0]
using enable_if_t = typename enable_if<_Cond, _Tp>::type;
GCC完全接受它。哪个编译器是正确的?
增加:
随着SFINAE在
template<int n, typename = std::enable_if_t<n == 0>>
...
template<int n, typename = std::enable_if_t<n == 1>>
GCC还产生一个错误的形式:
error: no matching function for call to ‘D::f<0>()’
d.f<0>();
^
note: candidate: template<int n, class> void D::f()
void f()
^
note: template argument deduction/substitution failed:
无关:您可能需要使用一个虚函数SFINAE基类和派生方法来区分,而不是。 –
@HenriMenke我不知道原始用例是什么,你也不知道,但是虚函数实现了与这里显示的完全不同的东西。这是利用实现继承,而不是多态,并且它使得这两个函数对于D的用户可用。虚拟是关于多态的,并且它只有一个可用于D的用户的功能。 –
@ Jarod42固定标签,谢谢。 – Evgeny