C++ return type overload hack

后端 未结 7 651
无人及你
无人及你 2021-02-04 09:02

I was bored and came up with such hack (pseudocode):

 1 struct proxy {
 2     operator int(); // int function
 3     operator double(); // double function
 4             


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 09:39

    I'd rather use template specialization, just feels less "hacky" and probably will be faster (no object creation, although of course that can be optimized away by smart compiler).

    But anyway, I'd rather see code like

    template T function();
    
    template<> int function() {
        return 1;
    }
    
    template<> float function() {
        return 1.0;
    }
    
    ....
    int a = function();
    float b = function();
    

    Nothing wrong with your code though, especially if you stay away from numeric types/pointers since otherwise unanticipated effects might occur, rules of conversion is quite complicated in C++.

提交回复
热议问题