SFINAE(enable_if)为什么不能用于类模板的成员函数? [英] Why doesn't SFINAE (enable_if) work for member functions of a class template?
问题描述
#include <type_traits>
struct A{};
struct B{};
template <typename T>
struct Foo
{
typename std::enable_if<std::is_same<T, A>::value>::type
bar()
{}
typename std::enable_if<std::is_same<T, B>::value>::type
bar()
{}
};
错误消息:
14:5: error: 'typename std::enable_if<std::is_same<T, B>::value>::type Foo<T>::bar()' cannot be overloaded 10:5:
error: with 'typename std::enable_if<std::is_same<T, A>::value>::type Foo<T>::bar()'
源于 cpp.sh 。我以为两个 typename std :: enable_if< std :: is_same< T,?> :: value> :: type
不能同时有效。
Source on cpp.sh. I thought both typename std::enable_if<std::is_same<T,?>::value>::type
could not be valid at the same time.
编辑
为了后代,这是我根据@KerrekSB的回答所做的编辑- SFINAE仅适用于推导的模板参数
For posterity here is my edit based on @KerrekSB's answer -- SFINAE only works for deduced template arguments
#include <type_traits>
struct A{};
struct B{};
template<typename T>
struct Foo
{
template<typename U = T>
typename std::enable_if<std::is_same<U,A>::value>::type
bar()
{
}
template<typename U = T>
typename std::enable_if<std::is_same<U,B>::value>::type
bar()
{
}
};
int main()
{
};
推荐答案
SFINAE仅适用于推论模板参数,即用于函数模板。在您的情况下,两个模板都无条件实例化,并且实例化失败。
SFINAE only works for deduced template arguments, i.e. for function templates. In your case, both templates are unconditionally instantiated, and the instantiation fails.
以下变体有效:
struct Foo
{
template <typename T>
typename std::enable_if<std::is_same<T, A>::value>::type bar(T) {}
// ... (further similar overloads) ...
};
现在 Foo()(x)
原因最多要实例化一个重载,因为参数替换在所有其他重载中均失败。
Now Foo()(x)
causes at most one of the overloads to be instantiated, since argument substitution fails in all the other ones.
如果您要坚持原始结构,请使用显式类模板专门化:
If you want to stick with your original structure, use explicit class template specialization:
template <typename> struct Foo;
template <> struct Foo<A> { void bar() {} };
template <> struct Foo<B> { void bar() {} };
这篇关于SFINAE(enable_if)为什么不能用于类模板的成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!