在重载解决期间,这不是一个错误。换句话说,它会推迟给你一个错误,直到它确定调用肯定不会工作。之后,这是一个错误。
struct example
{
template <typename T>
static void pass_test(typename T::inner_type); // A
template <typename T>
static void pass_test(T); // B
template <typename T>
static void fail_test(typename T::inner_type); // C
};
int main()
{
// enumerates all the possible functions to call: A and B
// tries A, fails with error; error withheld to try others
// tries B, works without error; previous error ignored
example::pass_test(5);
// enumerates all the possible functions to call: C
// tries C, fails with error; error withheld to try others
// no other functions to try, call failed: emit error
example::fail_test(5);
}
还应该注意,重载决议(以及因此 SFINAE)只查看函数签名,而不是定义。所以这总是会失败:
struct example_two
{
template <typename T>
static int fail_test(T x)
{
return static_cast<int>(x);
}
template <typename T>
static int fail_test(T x)
{
return boost::lexical_cast<int>(x);
}
};
int main()
{
example_two::fail_test("string");
}
任何一个模板替换(函数签名)都没有错误,所以这两个函数都可以调用,即使我们知道第一个会失败而第二个不会。所以这会给你一个模棱两可的函数调用错误。
boost::enable_if
您可以使用(或std::enable_if
在 C++0x 中,等效于)显式启用或禁用函数boost::enable_if_c
。例如,您可以使用以下方法修复前面的示例:
struct example_two_fixed
{
template <typename T>
static boost::enable_if<boost::is_convertible<T, int>, int>
pass_test(T x) // AA
{
return static_cast<int>(x);
}
template <typename T>
static boost::disable_if<boost::is_convertible<T, int>, int>
pass_test(T x) // BB
{
return boost::lexical_cast<float>(x);
}
};
struct empty {} no_conversion;
int main()
{
// okay, BB fails with SFINAE error because of disable_if, does AA
example_two::pass_test(5);
// okay, AA fails with SFINAE error because of enable_if, does BB
example_two::pass_test("string");
// error, AA fails with SFINAE, does BB, fails because cannot lexical_cast
example_two::pass_test(no_conversion);
}