C++ Template problem adding two data types

后端 未结 9 1327
慢半拍i
慢半拍i 2021-02-13 02:51

I have a template class with an overloaded + operator. This is working fine when I am adding two ints or two doubles. How do I get it to add and int and a double and return th

9条回答
  •  青春惊慌失措
    2021-02-13 03:43

    Newer answer to an old question. For C++0x you can go with decltype as other answers have talked about. I would argue that common_type is more made for the situation than decltype.

    Here is an example of common_type used in a generic add:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    template 
     array::type, N> // <- Gets the arithmetic promotion
     add_arrays(array u, array v)
    {
        array::type, N> result; // <- Used again here
        for (unsigned long i = 0; i != N; ++i)
        {
            result[i] = u[i] + v[i];
        }
        return result;
    }
    
    int main()
    {
        auto result = add_arrays( array {1, 2, 3, 4},
                                  array {1.0, 4.23, 8.99, 55.31} );
    
        for (size_t i = 0; i != 4; ++i)
        {
            cout << result[i] << endl;
        }
    
        return 0;
    }
    

    it basically returns the value that different arithmetic operations would promote to. One nice thing about it is that it can take any number of template args. Note: don't forget to add the ::type at the end of it. That is what gets the actual type result that you want.

    For those working pre-c++11 still, there is a boost version of common_type as well

提交回复
热议问题