【发布时间】:2016-10-16 07:47:31
【问题描述】:
重构遗留代码我想合并彼此相关的单独模板类/结构(以避免命名空间污染)。
Nested(下)是MyStruct 的辅助类,我想将其移入MyStruct。
但我无法完成这项工作:
#include <type_traits>
#include <iostream>
struct YES {} ;
struct NO {};
template <typename TYPE>
struct MyStruct
{
template <typename TYPE_AGAIN = TYPE, typename SELECTOR = NO>
struct Nested
{
static void Print(void)
{
std::cout << "MyStruct::Nested<bool = false>::Print()" << std::endl;
}
};
template <>
struct Nested<TYPE, typename std::enable_if<std::is_integral<TYPE>::value, YES>::type>
{
static void Print(void)
{
std::cout << "MyStruct::Nested<bool = true>::Print()" << std::endl;
}
};
};
编译器抱怨:
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
In file included from ../main.cpp:8:0:
../MyStruct.h:31:12: error: explicit specialization in non-namespace scope ‘struct MyStruct<TYPE>’
template <>
^
make: *** [main.o] Error 1
实际上,我也很困扰必须包括
<typename TYPE_AGAIN = TYPE>
但没有,还有更多的抱怨:
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
In file included from ../main.cpp:8:0:
../MyStruct.h:31:12: error: explicit specialization in non-namespace scope ‘struct MyStruct<TYPE>’
template <>
^
../MyStruct.h:32:9: error: template parameters not used in partial specialization:
struct Nested<typename std::enable_if<std::is_integral<TYPE>::value, YES>::type>
^
../MyStruct.h:32:9: error: ‘TYPE’
make: *** [main.o] Error 1
【问题讨论】:
标签: c++ c++11 templates sfinae