Cannot overload function

Posted by anio on Stack Overflow See other posts from Stack Overflow or by anio
Published on 2012-06-29T20:27:31Z Indexed on 2012/06/29 21:16 UTC
Read the original article Hit count: 229

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates