且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++中选择重载模板函数时的优先级

更新时间:2023-11-10 19:56:34

我找到了一个非常简单的解决方案!

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.