Overriding return type in function template specialization

前端 未结 4 1680
深忆病人
深忆病人 2020-12-04 07:49

I would like to specialize a function template such that the return type changes depending on the type of the template argument.

class ReturnTypeSpecializati         


        
4条回答
  •  悲哀的现实
    2020-12-04 08:35

    Perhaps you could use the following hack. Given these simple type traits:

    template
    struct conditional { typedef T type; };
    
    template
    struct conditional { typedef U type; };
    
    template
    struct is_same { static const bool value = false; };
    
    template
    struct is_same { static const bool value = true; };
    

    You could write your class and specialized member function as follows:

    class ReturnTypeSpecialization
    {
    public:
        template
        typename conditional::value, int, T>::type 
        Item();
    };
    
    // Normally just return the template type
    template
    typename conditional::value, int, T>::type
    ReturnTypeSpecialization::Item() { return T(); }
    
    // When a float is specified, return an int
    template<>
    int ReturnTypeSpecialization::Item() { return 1.0f; }
    

    Simple test program (uses C++11 just for verification):

    int main()
    {
        ReturnTypeSpecialization obj;
        static_assert(std::is_same()), bool>::value, "!");
        static_assert(std::is_same()), int>::value, "!");
    }
    

    Here is a live example.

提交回复
热议问题