C++ 成员模板特化语法

标签 c++ templates

关于 this site有以下段落:

When defining a member of an explicitly specialized class template outside the body of the class, the syntax template <> is not used, except if it's a member of an explicitly specialized member class template, which is specialized as a class template, because otherwise, the syntax would require such definition to begin with template< parameters > required by the nested template.

我不知道突出显示的部分是什么意思。 “否则”是指一般情况(不使用 template<>)还是异常(exception)情况(必须使用 template<>)?

我将不胜感激该部分的解释。

最佳答案

这将是我们的模板:

template< typename T>
struct A {
    struct B {};  // member class 
    template<class U> struct C { }; // member class template
};

请看下面的代码:

template<> // specialization
struct A<int> {
    void f(int); // member function of a specialization
};
// template<> not used for a member of a specialization
void A<int>::f(int) { /* ... */ }

我们没有使用 template<>同时定义特化的成员,因为这是一个普通的成员类。

但是,现在看下一段代码:

template<> // specialization of a member class template
template<class U> struct A<char>::C {
    void f();
};

// template<> is used when defining a member of an explicitly
// specialized member class template specialized as a class template
template<>
template<class U> void A<char>::C<U>::f() { /* ... */ }

这里我们特化了定义模板的成员模板。这就是为什么我们需要使用 template<>传递此成员模板需要的参数。在这种情况下 class U需要定义我们的成员模板,所以为了传递我们需要关键字 template<> .

关于C++ 成员模板特化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49792751/

相关文章:

c++ - 在 GDB 中反汇编重载的成员函数 - C++

使用 openGL 的 C++ 基本设置

c++ - Switch 语句可变模板扩展

c++ - 如何在 C++ 中设计库包装器?

c++ - vector 是否在 push_back() 上重新创建所有对象?

android - 使用 Android Studio 使用 native 代码编译 apk 时,如何在链接处删除 libgnuSTL_static.a?

c++ - 文件上的 2 次 XORcypher 加密不会产生相同的文件

C++ 访问继承类的成员,其中继承类是模板参数

c++ - 模板不能进行转换是什么意思?

templates - 模板中标记为 boost::bimap - 它们有效吗?