mmmmmmmm mmmmmmmm - 3 months ago 10
C++ Question

Priority when choosing overloaded template functions in C++

I have the following problem:

class Base
{
};

class Derived : public Base
{
};

class Different
{
};

class X
{
public:
template <typename T>
static const char *func(T *data)
{
// Do something generic...
return "Generic";
}

static const char *func(Base *data)
{
// Do something specific...
return "Specific";
}
};


If I now do

Derived derived;
Different different;
std::cout << "Derived: " << X::func(&derived) << std::endl;
std::cout << "Different: " << X::func(&different) << std::endl;


I get

Derived: Generic
Different: Generic


But what I want is that for all classes derived from Base the specific method is called.
So the result should be:

Derived: Specific
Different: Generic


Is there any way I can redesign the X:func(...)s to reach this goal?

EDIT:

Assume that it is not known by the caller of X::func(...) if the class submitted as the parameter is derived from Base or not. So Casting to Base is not an option.
In fact the idea behind the whole thing is that X::func(...) should 'detect' if the parameter is derived from Base or not and call different code.
And for performance reasons the 'detection' should be made at compile time.

Answer

I found a VERY easy solution!

class Base
{
};

class Derived : public Base
{
};

class Different
{
};

class X
{
private:
  template <typename T>
  static const char *intFunc(const void *, T *data)
  {
    // Do something generic...
    return "Generic";
  }

  template <typename T>
  static const char *intFunc(const Base *, T *data)
  {
    // Do something specific...
    return "Specific";
  }

public:
  template <typename T>
  static const char *func(T *data)
  {
    return intFunc(data, data);
  }
};

This works great and is very slim! The trick is to let the compiler select the correct method by the (otherwise useless) first parameter.