c++ - 推断 operator+ 和其他运算符的(模板化)返回类型

标签 c++ templates operator-overloading return-type

我正在实现一个二维 vector ,它的坐标可以采用任何算术类型。我想实现一个 operator+以与 unsigned x = 2l + 3.1; 相同的方式从上下文推断其返回类型的运算符知道 + 的结果应该是 unsigned因为它被分配给 unsigned .

到目前为止我所拥有的,灵感来自 Templates inferring type T from return type :

#include <array>
#include <type_traits>

template<typename T,
         typename = std::enable_if_t<std::is_arithmetic_v<T>, T>>
class Vec2
{
    std::array<T, 2> _data;

public:
    // Constructors
    Vec2(T x, T y): _data{x, y} {}

    // Operators
    template<typename TB, // second operand's coordinates type
             typename TR> // result's coordinates type
    Vec2<TR> operator+(const Vec2<TB> v) const
    {
        return Vec2<TR>(_data[0] + v._data[0],
                        _data[1] + v._data[1]);
    }
};

int main(void)
{
    Vec2 vi{0, 2};
    Vec2 vf{1.4, 2.2};

    Vec2<int> res = vi + vf;
}

我收到一条错误消息,说它无法推断用于返回值的类型:
$ g++ -Wall -Wextra -std=c++17 poc.cc
poc.cc: In function ‘int main()’:
poc.cc:29:24: error: no match for ‘operator+’ (operand types are ‘Vec2<int, int>’ and ‘Vec2<double, double>’)
   29 |     Vec2<int> res = vi + vf;
      |                     ~~ ^ ~~
      |                     |    |
      |                     |    Vec2<double,double>
      |                     Vec2<int,int>
poc.cc:17:14: note: candidate: ‘template<class TB, class TR> Vec2<TR> Vec2<T, <template-parameter-1-2> >::operator+(Vec2<TB>) const [with TB = TB; TR = TR; T = int; <template-parameter-1-2> = int]’
   17 |     Vec2<TR> operator+(const Vec2<TB> v) const
      |              ^~~~~~~~
poc.cc:17:14: note:   template argument deduction/substitution failed:
poc.cc:29:26: note:   couldn’t deduce template parameter ‘TR’
   29 |     Vec2<int> res = vi + vf;
      |                          ^~
poc.cc:29:15: warning: unused variable ‘res’ [-Wunused-variable]
   29 |     Vec2<int> res = vi + vf;
      |               ^~~

最佳答案

在 C++ 中,+运算符重载无法确定其结果将分配给什么。 C++ 根本就不能这样工作。

在许多情况下,可以以略有不同的方式设计替代方案。首先拥有 +运算符(operator)弄清楚它的最佳返回类型应该是什么:

template<typename TB> // result's coordinates type
auto operator+(const Vec2<TB> v) const
{
    typedef decltype( static_cast<T>(0) + static_cast<TB>(0) ) ret_t;

    return Vec2<ret_t>(_data[0] + v._data[0],
                    _data[1] + v._data[1]);
}

您确保 TTB是算术类型,所以这是通过 decltype 计算出来的最简单方法.

所以,添加一个 Vec2int s 到 Vec2double s 应该产生一个 Vec2<double> .但是如果这被分配给 Vec2<int> 呢? ?好吧,您只需要一个转换运算符...
template<typename TB>
operator Vec2<TB>() const
{
    return Vec2<TB>(_data[0], _data[1]);
}

......并希望最好。

关于c++ - 推断 operator+ 和其他运算符的(模板化)返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60137501/

相关文章:

android - Android OpenCV 中传出字节 [] 需要 cv::imencode 吗?

c++ - 模板之间的隐式转换

c++ - 变量参数列表如何与 C++ 中的重载对象一起使用?

C++在可变参数模板内专门化可变参数模板

c++ - 模板函数指针作为模板参数

c++ - 运算符==比较两个不同的类

c++11 - 带有映射的结构的 ostream 运算符重载

c++ - 如何在 mac 上的 sublime text 2 上运行 C++?

c++ - 读取字符显示所有字符后跟一些垃圾字符

c++ - 从 std::runtime_error 私有(private)继承的类未被捕获为 std::exception