为什么 A 中的特化 S 合法而 B 中的 S 不合法?
(如果 B 没有被注释掉) GCC 4.8.1:错误:在非 namespace 范围“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;
}
最佳答案
@jrok 的评论几乎可以解释您的编译器错误。一般而言,嵌套类,尤其是嵌套类模板,是您可以轻松避免的语言的一个尘土飞扬的角落(牢记 Sutter 的建议“Write what you know and know what you write”)。
简单地制作一个命名空间细节
来定义你的类模板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
,那么如果您还特化了封闭类,则只能特化嵌套类模板。简而言之:只需通过额外的编译时间接级别来完全避免这些问题。
关于c++ - 类范围内的类模板特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18904587/