Priority when choosing overloaded template functions in C++

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

    You must use SFINAE for this. In the following code, the first function can be instantiated if and only if you pass something that can't be (implicitly) converted to Base *. The second function has this reversed.

    You might want to read up on enable_if.

    #include 
    #include 
    #include 
    
    class Base {};
    class Derived : public Base {};
    class Different {};
    
    struct X
    {
        template 
        static typename boost::disable_if,
            const char *>::type func(T *data)
        {
            return "Generic";
        }
    
        template 
        static typename boost::enable_if,
            const char *>::type func(T *data)
        {
            return "Specific";
        }
    };
    
    int main()
    {
        Derived derived;
        Different different;
        std::cout << "Derived: " << X::func(&derived) << std::endl;
        std::cout << "Different: " << X::func(&different) << std::endl;
    }
    

提交回复
热议问题