In C , SFINAE (Substitution Failure Is Not An Error) allows you to enable or disable code depending on the type of a template argument. However, when dealing with member functions of a class template, SFINAE often doesn't work as expected.
Here's an example that demonstrates the issue:
#include
struct A {};
struct B {};
template
struct Foo
{
typename std::enable_if<:is_same a>::value>::type bar()
{}
typename std::enable_if<:is_same b>::value>::type bar()
{}
};
In this example, Foo defines two overloaded member functions bar(). The first overload is enabled when T is A, and the second is enabled when T is B. However, if you try to compile this code, you'll get an error message indicating that the overloads cannot be resolved.
The reason for this error is that SFINAE only works for deduced template arguments. In the case of member functions of a class template, the template argument is not deduced but rather specified explicitly. To fix the issue, you can use one of the following techniques:
Use explicit template arguments:
struct Foo
{
void bar(A) {}
void bar(B) {}
};
Use std::enable_if inside the member functions:
template
struct Foo
{
template
typename std::enable_if<:is_same a>::value>::type bar() {}
template
typename std::enable_if<:is_same b>::value>::type bar() {}
};
Use explicit class template specialization:
template struct Foo { void bar() {} };
template struct Foo { void bar() {} };
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3