Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot overload function

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.

like image 265
anio Avatar asked Sep 26 '26 07:09

anio


1 Answers

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!

like image 69
templatetypedef Avatar answered Sep 27 '26 19:09

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!