问题描述
我下面有一些代码,我希望具有不同专业的TestEnableIf具有不同的打印功能,但是它没有按计划进行,出现以下错误.
I have below code that I want TestEnableIf with different specialization to have different print function, but it didn't work out as planned, with error as below.
struct myStruct;
struct notMyStruct;
template<typename T> struct TestEnableIf
{
template<typename boost::enable_if< boost::is_same<myStruct, T>, int >::type = 0> void print()
{
std::cout << "this is my struct" << std::endl;
}
template<typename boost::enable_if< boost::is_same<notMyStruct, T>, int>::type=0> void print()
{
std::cout << "This is not my struct" << std::endl;
}
};
static void testIsSame()
{
TestEnableIf<myStruct> testEnable;
testEnable.print();
TestEnableIf<notMyStruct> testNotEnable;
testNotEnable.print();
}
我不明白的是,sfinae表示专业化失败不是错误,那么编译器为什么要抱怨失败?
What I don't understand is, should sfinae mean specialization failure is not an error, then why should the compiler complain about the failure?
推荐答案
SFINAE(顺便说一下,S是替代",而不是专业化")不适用于类类型参数.解决该问题的一种简单方法是使用另一个模板参数:
SFINAE (the S is "substitution", not "specialization", by the way) for member functions does not work this way with class type parameters. A simple way to get around that is to use another template parameter:
template<
typename TCopy = T
typename boost::enable_if< boost::is_same<myStruct, TCopy>, int >::type = 0
> void print()
{
std::cout << "this is my struct" << std::endl;
}
我从 STL的CppCon谈话中撤了下来. TL; DW:使用类的T
类型参数时,编译器在实例化类模板时知道该类型是什么,并会在该时间点检查type
成员.使用额外的TCopy
类型参数位于函数本地时,编译器无法确定,直到实例化该函数为止,此时SFINAE可能会跳入以影响调用的重载设置.
I pulled this from STL's CppCon talk. TL;DW: when using the class's T
type parameter, the compiler knows what that type is when instantiating the class template and would check for the type
member at that point in time. With the extra TCopy
type parameter being local to the function, the compiler cannot know for sure until the function is instantiated, at which point SFINAE can jump in to affect the overload set for the call.
这篇关于C ++模板sfinae错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!