Why doesn't my templated function promote 'int' to 'T', where 'T' = 'double'?

前端 未结 3 1259
无人及你
无人及你 2021-02-05 07:21

I have a class templated with typename T. It contains a function,

template 
myClass operator+(myClass

        
3条回答
  •  庸人自扰
    2021-02-05 07:52

    You are running into problems with template type deduction.

    Both arguments are given "equal standing" when deducing the value of T, and in this case the two arguments disagree -- one says T should be int, the other says T should be double.

    The right way to fix this is with Koenig operators.

    Make += and + and the like friends of your class and implement inline:

    template
    class myClass {
      // etc
    public:
      friend myClass operator+(myClass lhs, const T& rhs) {
        lhs += rhs;
        return std::move(lhs);
      }
      friend myClass& operator+=(myClass& lhs, const T& rhs) {
        // do addition, depends on `a`
        return *this;
      }
    };
    

    this technique does something strange. It creates non-template operators based on the template type of the class. These are then found via ADL (Koenig lookup) when you invoke + or +=.

    You get one of these operators per template instantiation, but they aren't template operators, so const T& isn't deduced, and conversion happens as expected.

提交回复
热议问题