c++ - 专门化模板定义中的模板成员

标签 c++ templates

可以在模板定义之外特化一些类成员函数:

template<class A>
struct B {
   void f();   
};

template<>
void B<int>::f() { ... }

template<>
void B<bool>::f() { ... }

在这种情况下,我什至可以省略通用类型 A 的函数 f 的定义。

但是如何将这个特化放在类中呢?像这样:

template<class A>
struct B {
   void f();   

   void f<int>() { ... }
   void f<bool>() { ... }
};

在这种情况下我应该使用什么语法?

编辑: 目前,代码行最少的解决方案是添加一个伪造的模板函数 f 定义,并从原始函数 f 中显式调用它:

template<class A>
struct B {
   void f() { f<A>(); }

   template<class B> 
   void f();

   template<> 
   void f<int>() { ... }

   template<> 
   void f<bool>() { ... }
};

最佳答案

你应该把特化放在struct上:

template<>
struct B<int> {
   void f() { ... }
};

template<>
struct B<bool> {
   void f() { ... }
};

无法在定义模板版本的同一个类中特化成员函数。您必须在类外部显式特化成员函数,或者特化整个类,其中包含成员函数。

关于c++ - 专门化模板定义中的模板成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10233734/

相关文章:

c++ - 即用户代理wxWidgets

c++ - 将组合框信号连接到 Qt 中的 std::function 的问题

c++ - 在使用 yacc 和 lex 的 CodeBlocks/Eclipse 中构建 C++ 项目

python - 有什么方法可以让这个Python字符串语句更加Pythonic吗?

c++ - 运行时数据类型多态性

c++ - 改进使用 MFC FindFile API 失败

c++ - 为什么 T 在这里不推导为 int&&

c++ - 一个类可以有将当前类作为参数的成员吗

python - django-pagination 包中的 CSS 类

c++ - 为什么类不能继承其父类的成员类型?