如何为模板化类的模板化函数定义模板专用化

How to define a template specialization for a templated function for a templated class

本文关键字:函数 定义 专用      更新时间:2023-10-16

我有一个类,类似于下面的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=intBar=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
}