为什么A中的专业化S和B中的S不是?
(如果B没有注释掉)
GCC 4.8.1:错误:非命名空间范围'B类'中的显式特化
#include <type_traits>
#include <iostream>
class Y {};
class X {};
struct A {
template<class T, class = void>
class S;
template<class T>
struct S < T, typename std::enable_if< std::is_same< Y, T >::value >::type >
{
int i = 0;
};
template<class T>
struct S < T, typename std::enable_if< std::is_same< X, T >::value >::type >
{
int i = 1;
};
};
/*
class B
{
template<class T>
class S;
template<>
class S < Y > {};
template<>
class S < X > {};
};
*/
int main()
{
A::S< X > asd;
std::cout << asd.i << std::endl;
}
在coliru:B评论说
在coliru:与B(错误)
@jrok的评论几乎解释了你的编译器错误。一般来说,嵌套类,特别是嵌套类模板,是你可以轻松避免的语言的一个尘土飞扬的角落(深入了解Sutter的建议)写下你所知道的,知道你写的是什么“)。
简单地做一个 namespace detail
定义类模板 SA
和 SB
和他们的专业,然后定义嵌套模板类型别名 S
里面两个 A
和 B
namespace detail {
template<class T, class = void>
class SA;
template<class T>
struct SA < T, typename std::enable_if< std::is_same< Y, T >::value >::type >
{
int i = 0;
};
template<class T>
struct SA < T, typename std::enable_if< std::is_same< X, T >::value >::type >
{
int i = 1;
};
template<class T>
class SB;
template<>
class SB < Y > {};
template<>
class SB < X > {};
}
struct A
{
template<class T>
using S = detail::SA<T>;
};
struct B
{
template<class T>
using S = detail::SB<T>;
};
当然,对于这种情况,它似乎有点矫枉过正,但如果你想做的话 A
和 B
类模板本身,并专门化 A
和 B
,如果你也专门化封闭类,那么你只能专门化嵌套类模板。简而言之:只需通过额外的编译时间点间接来避免这些问题。