Overriding return type in function template specialization

前端 未结 4 1678
深忆病人
深忆病人 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:22

    Since the specialization has to agree with the base template on the return type, you can make it so by adding a "return type trait", a struct you can specialize and draw the true return type from:

    // in the normal case, just the identity
    template
    struct item_return{ typedef T type; };
    
    template
    typename item_return::type item();
    
    template<>
    struct item_return{ typedef int type; };
    template<>
    int item();
    

    Live example.

    Note that you might want to stick to the following, so you only need to update the return-type in the item_return specialization.

    template<>
    item_return::type foo(){ ... }
    // note: No `typename` needed, because `float` is not a dependent type
    

提交回复
热议问题