C++ 类对非类型模板参数的部分特化

标签 c++ templates

我不确定我的术语是否正确,但我认为我有一个包含类型和非类型模板参数的类模板,并且我想单独部分地专门研究非类型参数:

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<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/

相关文章:

c++ - 我将如何着手将天空盒应用于世界,openGL C++

c++ - 为什么要将两个 32 位整数组合成一个 64 位整数?

c++ - 使用 const 成员对自定义对象的 vector 进行排序

c++ - 带模板的条件返回类型

Oracle Apex 模态对话框链接被错误转换

templates - 在 Joomla 2.5 中,如何在模板中回显文章的 "Link A"值?

c++ - 0x771515ee 处未处理的异常 Microsoft C++ 异常:内存位置 0x0049f904 处的 std::bad_alloc

c++ - 在插入其他线程时有效地遍历 map

c++ - 如何为我的类生成一个 std::get 类函数?

c++ - 函数重载和模板推导优先级