Priority when choosing overloaded template functions in C++

后端 未结 6 428
不思量自难忘°
不思量自难忘° 2020-12-09 03:35

I have the following problem:

class Base
{
};

class Derived : public Base
{
};

class Different
{
};

class X
{
public:
  template 
  stat         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 04:28

    I found a VERY easy solution!

    class Base
    {
    };
    
    class Derived : public Base
    {
    };
    
    class Different
    {
    };
    
    class X
    {
    private:
      template 
      static const char *intFunc(const void *, T *data)
      {
        // Do something generic...
        return "Generic";
      }
    
      template 
      static const char *intFunc(const Base *, T *data)
      {
        // Do something specific...
        return "Specific";
      }
    
    public:
      template 
      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.

提交回复
热议问题