Priority when choosing overloaded template functions in C++

后端 未结 6 426
不思量自难忘°
不思量自难忘° 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:42

    If you are using boost, you can do it with some template metaprogramming:

    #include 
    
    class X
    {
    private:
        template 
        static const char *generic_func(T *data)
        {
            // Do something generic...
            return "Generic";
        }
    
        template 
        static const char *base_func(T *data)
        {
            // Do something specific...
            return "Specific";
        }
    
    public:
        template 
        static const char* func(T* data)
        {
            if (boost::is_base_of::value)
                return base_func(data);
    
            return generic_func(data);
        }
    };
    

    The is_base_of metafunction is evaluated at compile time and the optimizer will most probably remove the dead branch of the if in the func function. This approach allows you to have more than one specific case.

提交回复
热议问题