我不确定我的术语是否正确,但我认为我有一个包含类型和非类型模板参数的类模板,并且我想单独部分地专门研究非类型参数:
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 list
和error C2976: 'A<T,I>': too few template arguments
.
但是,如果我删除类型参数,那么我似乎可以专注于非类型参数:
template<int I> struct B
{
void g();
};
void B<1>::g() {}
int main()
{
B<1> b1;
b1.g();
}
那么我想要的东西是不可能的,还是我只是没有以正确的方式做?如果不可能,有其他选择吗?
最佳答案
让我们考虑一下 standard 是什么? (工作草案)说:
A member [...] of a class template may be explicitly specialized for a given implicit instantiation of the class template, even if the member [...] is defined in the class template definition. An explicit specialization of a member [...] is specified using the syntax for explicit specialization.
换句话说,您尝试做的事情是不允许的。
仅此而已。
想象一下,如果是的话,你也可以这样做:
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<int, 1>
的实例化无法进一步特化。
换句话说,在这种情况下您不能执行此操作:
template<>
struct A<int, 1> {};
f
的存在因此在某种程度上保证。
关于C++ 类对非类型模板参数的部分特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41574134/