C++ Template problem adding two data types

后端 未结 9 1316
慢半拍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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 03:23

    Stephen has already given a good explanation of the problems you may encounter with this. You can define overloads for all the possible combinations of all the instantiations of the template (so, you'd effectively have operators defined for double + double, int + double, double + int, etc.). This can get unwieldy fast and can be difficult to keep track of which combinations are supported.

    You might be better off using a non-member function named something like Add(). The advantage of doing this is that you can specify the return type. The disadvantage is that you have to specify the return type. :-) In general, though, this is better than performing unexpected conversions automatically.

    template 
    TemplateTest Add(const TemplateTest& t, const TemplateTest& u)
    {
        return TemplateTest(t.x + u.x);
    }
    

    invoked as:

    std::cout << Add(intTt1, doubleTt1) << std::endl;
    

    C++0x will add support for a number of language features that will make this much simpler and will allow you to write a reasonable operator+ overload:

    template 
    auto operator+(const TemplateTest& t, const TemplateTest& u) 
        -> TemplateTest
    {
        return TemplateTest(t.x + u.x);
    }
    

    This will ensure that the usual arithmetic conversions (integer promotion, conversion to floating point, etc.) are performed and you end up with the expected result type.

    Your C++ implementation may support these C++0x features already; you'd want to consult the documentation of whatever compiler you are using.

提交回复
热议问题