【发布时间】:2023-03-27 08:00:01
【问题描述】:
我正在使用模板和部分专业化,但有一个专业化我不知道如何编写...我将简化代码以使其更易于阅读。
让我们考虑
template <typename T>
class x
{
...
};
通常,我可以这样专攻:
class x<a_type>
{
...
};
也适用于模板类型:
template <typename T>
class x<std::vector<T>>
{
...
}
现在我想对嵌套在模板类中的类型进行特化:
template <typename T>
class y
{
struct nested_type
{
y a_member;
};
...
};
// Here comes the specialization
template <typename T>
class x<y<T>::nested_type>
{
...
};
这失败了。我还尝试将 'typename' 放在 y::nested_type 之前,但它并没有解决问题。编译错误是:
type/value mismatch at argument 1 in template parameter list for ‘template <class T> struct x’
我想做的事情似乎合乎逻辑,但我不确定它是否可能。我将 C++0x 与 g++-4.5 一起使用。有人知道编写这种专业化的正确语法吗?
【问题讨论】:
-
我认为您需要编辑问题。它应该是
class x<....>,而不是前两个块中的class<....>。你确定你已经仔细输入了 everything 吗? -
是的,你是对的。这只是我的消息中的一个小错误,因为我没有复制我的代码,而是更喜欢使用
x或y来简化问题。我确实尝试了较小的示例,但 Mikael 的答案似乎不错 - 我无法使小示例起作用,相信我,我尝试了很多东西! -
请注意,如果您使用“正确”语法
template<typename T> class x<typename y<T>::nested_type>而不是template<typename T> class x<y<T>::nested_type>(添加typename),则会从GCC 收到更合理的错误消息。
标签: c++ templates specialization