重構遺留代碼我想合併彼此相關的單獨模板類/結構(以避免命名空間污染)。模板類中的類模板特殊化
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
非常感謝! - 這個模板<>模板<>語法對我來說是新的。 –
好吧,似乎我太快把這作爲解決我的問題。 –
我仍然在圈子中跑步。完全專門化外部類MyClass是不好的。我想利用由MyClass的模板參數驅動的內部類嵌套。看起來,這是不可能的?或者它只是「糟糕的設計」 - 我們必須爲此使用外部策略類並且不能將其嵌入到MyClass中? –