如何为模板化类的模板化函数定义模板专用化
How to define a template specialization for a templated function for a templated class
我有一个类,类似于下面的BizClass
。我想为特定具体类型定义一个模板化函数和一个专用化。我不确定适当的语法。
template <class Foo>
class BizClass {
public:
template <typename Bar>
void Action(Container<Bar> m);
// Foo is used somewhere else...
};
// This seems to work.
template <class Foo>
template <typename Bar>
inline void BizClass<Foo>::Action(Container<Bar> m) {}
// This specialization doesn't compile, where Foobar is a concrete class.
template <class Foo>
inline void BizClass<Foo>::Action(Container<FooBar> m) {}
如何处理此案例的模板专用化?
在第一个标题为This seems to work.
的代码示例中,这只是定义模板函数的主体,它不是专用的。
在第二个示例中,您尝试专用化作为另一个非专用模板成员的模板。这是不允许的。
如果你想专攻Action
,你还需要专攻BizClass
,例如,这里有一个Foo=int
和Bar=char
的例子:
template<> template<>
inline void BizClass<int>::Action(Container<char> m)
{
}
如何处理这种情况的模板专用化?
据我所知,C++禁止在模板结构/类中对方法进行专用化,而不对结构/类本身进行专用化。
但是您可以使用重载:使Action (Container<FooBar> m)
成为非模板方法
#include <iostream>
template <typename>
struct Container
{ };
struct FooBar
{ };
template <typename Foo>
struct BizClass
{
template <typename Bar>
void Action (Container<Bar> m);
void Action (Container<FooBar> m);
};
template <typename Foo>
template <typename Bar>
inline void BizClass<Foo>::Action (Container<Bar> m)
{ std::cout << "Action() generic version" << std::endl; }
template <typename Foo>
inline void BizClass<Foo>::Action (Container<FooBar> m)
{ std::cout << "Action() FooBar version" << std::endl; }
int main ()
{
BizClass<int> bci;
bci.Action(Container<int>{}); // print Action() generic version
bci.Action(Container<FooBar>{}); // print Action() FooBar version
}
相关文章:
- 不同翻译单元中不可重载的非内联函数定义
- Visual Studio中的函数声明和函数定义问题
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 具有enable_if外部类原型的模板类构造函数定义
- 类的前向声明之后的类成员函数定义,在类声明之前
- 为函数定义符号不明确的指针参数
- C++模板专用化 - 无法匹配函数定义
- 错误:在第 6 行'{'标记之前,此处不允许使用函数定义
- 找不到 #define 的函数定义
- 根据类型特征更改函数定义?
- 将抽象基类中的所有纯虚函数定义为 varaidaic 模板
- 命名空间更改函数定义
- "Type&"与C++函数定义中的"Type*"
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 如何从 C++ 中的现有模板函数定义新函数
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- 为什么c++允许成员函数定义中实例的私有成员访问
- Qt基类函数定义
- C++函数定义中参数列表后面额外一对括号的含义