C++ 为什么编译器不接受基于enable_if的专门化
我想为某些类型的类专门化类,例如基于std::is_算法的类。尽管编译器并没有“看到”我基于“enable_if”的专门化,而是选择了principle/main模板。你能帮我做这个吗。。。 下面是使用g++4.8编译后的代码片段和输出C++ 为什么编译器不接受基于enable_if的专门化,c++,c++11,template-specialization,enable-if,C++,C++11,Template Specialization,Enable If,我想为某些类型的类专门化类,例如基于std::is_算法的类。尽管编译器并没有“看到”我基于“enable_if”的专门化,而是选择了principle/main模板。你能帮我做这个吗。。。 下面是使用g++4.8编译后的代码片段和输出 #include < iostream > #include < type_traits > #include < string > template < typename T1, typename T2
#include < iostream >
#include < type_traits >
#include < string >
template < typename T1, typename T2 = void >
struct TestT
{
static const bool is_int = false;
static const bool is_str = false;
};
template < typename T>
struct TestT < T,
std::enable_if< std::is_arithmetic<t>::value, T >::type >
{
static const bool is_int = true;
static const bool is_str = false;
};
template < typename T>
struct TestT < std::string, T >
{
static const bool is_int = false;
static const bool is_str = true;
};
class enum TestE
{
Last
};
int main(int argc, char* argv[])
{
std::cout << "Enum is_int: " << TestT<TestE>::is_int
<< ", is_str: " << TestT<TestE>::is_str << std::endl;
std::cout << "string is_int: " << TestT<std::string>::is_int
<< ", is_str: " << TestT<std::string>::is_str << std::endl;
std::cout << "int is_int: " << TestT<int>::is_int
<< ", is_str: " << TestT<int>::is_str << std::endl;
return 0;
}
#包括
#包括
#包括
模板
结构测试
{
静态常数bool为_int=false;
静态常量布尔为_str=false;
};
模板
结构TestT::类型>
{
静态常数布尔为整=真;
静态常量布尔为_str=false;
};
模板
结构TestT
{
静态常数bool为_int=false;
静态常数布尔为_str=true;
};
类枚举测试
{
最后
};
int main(int argc,char*argv[])
{
std::cout您需要保留第二个参数(别名为::type
)未指定或void
,以便与主模板的默认参数匹配:
struct TestT
在std::enable_if
语句之前还需要typename
,或者使用std::enable_if_t
(并省略::type
):
struct TestT
第二个专门化也是如此:
模板
结构测试
{
静态常数bool为_int=false;
静态常数布尔为_str=true;
};
最后,在这个专门化中,is_int
应该设置为true
:
模板
结构测试
{
静态常数布尔为整=真;
静态常量布尔为_str=false;
};
更好的版本可能是保留一个专门化,并使用std::is_same
测试int
和一个类型特征测试字符串:
templatestruct是_字符串:std::false_类型{};
templatestruct是_字符串:std::true_类型{};
templatestruct是_字符串:std::true_类型{};
templatestruct是_字符串:std::true_类型{};
templatestruct是_字符串:std::true_类型{};
templatestruct是_字符串:std::true_类型{};
//不停地。。。
模板
结构测试
{
静态常量bool is_int=std::is_same();
静态常量bool is_str=is_string();
};
请发布一些编译的代码我正在点击检查链接,不过您能解释一下为什么第二个参数必须与主模板匹配吗。如果要查看第二个专门化,对于std::string,第二个参数不匹配,但它适用于string@Yurishd这是我的疏忽,std::stri的专业化ng
应在专用化中具有void
或空的第二个参数。其工作的原因是模板比主模板更专用(第一个参数采用std::string
,第二个参数采用任何参数)。因此选择了它。正确的代码应为: