C++ Template problem adding two data types

后端 未结 9 1317
慢半拍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:25

    The add operator should generally be a free function to avoid preferring any operand type as @Stephen nicely explains. This way it's completely symmetric. Assuming you have a function get that returns the stored value, this can be like the following (alternatively, you can declare it as a friend if such a get function does not exist)

    template
    TemplateTest operator+(const TemplateTest& t1, const TemplateTest& t2)
    {
      return TemplateTest(t1.get() + t2.get());
    }
    

    The problem now is to find a result type. As other answers show this is possible with decltype in C++0x. You can also simulate this by using the rules of the ?: operator which are mostly quite intuitive. promote<> is a template that uses that technique

    template
    TemplateTest< typename promote::type > 
    operator+(const TemplateTest& t1, const TemplateTest& t2)
    {
      return TemplateTest< typename promote::type >(t1.get() + t2.get());
    }
    

    Now for example if you add double and int, it will yield double as the result. Alternatively as shown in the promote<> answer, you can also specialize promote so you can apply it directly to TemplateTest types.

提交回复
热议问题