【问题标题】:C++ Class partial specialization on non-type template parameter非类型模板参数的 C++ 类部分特化
【发布时间】:2017-01-10 16:54:36
【问题描述】:

我不确定我得到的术语是否正确,但我认为我有一个包含类型和非类型模板参数的类模板,我想仅部分专注于非类型参数:

template<class T, int I> struct A
{
    void f();
};

template<class T> void A<T, 1>::f() {}

int main()
{
    A<int, 1> a1;
    a1.f();
}

使用 Visual C++ 我得到 error C3860: template argument list following class template name must list parameters in the order used in template parameter listerror C2976: 'A&lt;T,I&gt;': too few template arguments

但是,如果我删除类型参数,那么我似乎可以专注于非类型参数:

template<int I> struct B
{
    void g();
};

void B<1>::g() {}

int main()
{
    B<1> b1;
    b1.g();
}

那么我想要的东西是不可能的,还是我没有以正确的方式做到这一点?如果不行,有没有其他办法?

【问题讨论】:

标签: c++ templates


【解决方案1】:

让我们考虑一下standard(工作草案)的内容:

类模板的成员 [...] 可以显式地专门用于类模板的给定隐式实例化,即使成员 [...] 是在类模板定义中定义的。成员 [...] 的显式特化是使用显式特化的语法指定的。

换句话说,您尝试做的事情是不允许的。
就是这样。


想象一下,如果是这样的话,你也会被允许这样做:

template<class T, int>
struct A { void f(); };

template<typename T>
void A<T, 1>::f() {}

template<>
struct A<int, 1> {};

也就是说,为类模板定义f,该类模板的特化甚至不能声明f
这没有多大意义,不是吗?

另一方面,考虑以下成员专业化:

template<>
void A<int, 1>::f() {}

它会导致无法进一步专门化的 A&lt;int, 1&gt; 的实例化。
换句话说,在这种情况下你不能这样做:

template<>
struct A<int, 1> {};

f 的存在以某种方式保证因此。

【讨论】:

  • 谢谢,这是有道理的。由于需要重复如此多的代码(实际上这是一门大课),我回避了整个课程的部分专业化。但我现在看到它必须以这种方式工作。
猜你喜欢
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多