I have a class, something like BizClass
below. I'd like to define a templated function and a specialization for a particular concrete type. I'm not sure of the appropriate syntax.
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) {}
How do I handle the template specialization for this case?
How do I handle the template specialization for this case?
As far I know, the C++ forbids specialization of a method, inside a template struct/class, without specializing the struct/class itself.
But you can use overloading: make Action (Container<FooBar> m)
a not-template method
#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
}
In your first code sample titled This seems to work.
, that is just defining the body for the template function, it is not a specialization.
In the second sample you attempt to specialize a template which is a member of another unspecialized template. This is not allowed.
You need to also specialize BizClass
if you want to specialize Action
, eg here is an example with Foo=int
and Bar=char
:
template<> template<>
inline void BizClass<int>::Action(Container<char> m)
{
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.