2017-08-08 84 views
5

微软编译器(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: 
+0

无关:您可能需要使用一个虚函数SFINAE基类和派生方法来区分,而不是。 –

+0

@HenriMenke我不知道原始用例是什么,你也不知道,但是虚函数实现了与这里显示的完全不同的东西。这是利用实现继承,而不是多态,并且它使得这两个函数对于D的用户可用。虚拟是关于多态的,并且它只有一个可用于D的用户的功能。 –

+0

@ Jarod42固定标签,谢谢。 – Evgeny

回答

2

谈到cppleaner的评论到一个答案:

namespace.udecl#15.sentence-1

When a using-declarator brings declarations from a base class into a derived class, member functions and member function templates in the derived class override and/or hide member functions and member function templates with the same name, parameter-type-list, cv-qualification, and ref-qualifier (if any) in a base class (rather than conflicting)

不幸的是,模板参数不计及两个f具有空参数类型列表,不是const的,没有REF-预选赛。

Derived::f因此隐藏Base::f

gcc接受该代码是错误的。

因此,要解决它是默认参数的方式(返回类型也不算):

struct B 
{ 
    template <int n> 
    void f(std::enable_if_t<n == 0>* = nullptr) { } 
}; 

struct D : B 
{ 
    using B::f; 
    template <int n> 
    void f(std::enable_if_t<n == 1>* = nullptr) { } 
};