问题
So I've got a templatized class and I want to overload the behavior of a function when I have specific type, say char. For all other types, let them do their own thing. However, c++ won't let me overload the function.
Why can't I overload this function? I really really do not want to do template specialization, because then I've got duplicate the entire class.
Here is a toy example demonstrating the problem: http://codepad.org/eTgLG932
The same code posted here for your reading pleasure:
#include <iostream>
#include <cstdlib>
#include <string>
struct Bar
{
std::string blah() { return "blah"; }
};
template <typename T>
struct Foo
{
public:
std::string doX()
{
return m_getY(my_t);
}
private:
std::string m_getY(char* p_msg)
{
return std::string(p_msg);
}
std::string m_getY(T* p_msg)
{
return p_msg->blah();
}
T my_t;
};
int main(int, char**)
{
Foo<char> x;
Foo<Bar> y;
std::cout << "x " << x.doX() << std::endl;
return EXIT_SUCCESS;
}
Thank you everyone for your suggestions. Two valid solutions have been presented. I can either specialize the doX method, or specialize m_getY() method.
At the end of the day I prefer to keep my specializations private rather than public so I'm accepting Krill's answer.
回答1:
You can make your method m_getY
a member function template. And them make specialization of this function template for char*
or simply define a method with a char*
argument. In this case you will not have to duplicate the whole class.
回答2:
You can specialize just one function out of an entire template class on a specific type without specializing the entire class. It would look like this:
template <> void Foo<char>::doX() {
/* custom implementation here */
}
You rarely see this in practice, but this is totally legal C++ code.
Hope this helps!
回答3:
std::string m_getY(char* p_msg)
{
return std::string(p_msg);
}
std::string m_getY(T* p_msg)
{
return p_msg->blah();
}
The problem here is that when T
is char
, you end up with two functions with identical signature.
回答4:
std::string m_getY(char* p_msg)
{
return std::string(p_msg);
}
template<typename U>
std::string m_getY(U* p_msg)
{
return p_msg->blah();
}
will not conflict with each other (and the former is not a specialisation of the latter, as it is not a template)
来源:https://stackoverflow.com/questions/11268535/cannot-overload-function