gpt4 book ai didi

c++ - 用户定义的转换运算符不适用于引用

转载 作者:太空宇宙 更新时间:2023-11-04 16:01:38 24 4
gpt4 key购买 nike

我有一个简单的原始类型包装器:

template <typename T>
class Scalar {
public:
explicit Scalar(T value) : value{value} {}

Scalar(Scalar&& other) = default;
Scalar& operator=(Scalar&& other) = default;
Scalar(const Scalar& other) = default;
Scalar& operator=(const Scalar& other) = default;

template <typename U>
explicit operator Scalar<U>() {
return Scalar<U>{static_cast<U>(this->value)};
}

inline T getValue() const noexcept { return this->value; }
private:
T value;
};

转换标量值效果很好,但不知何故它无法引用,例如

auto a = Scalar<double>{2.54};
Scalar<int> b = static_cast<Scalar<int>>(a); // works

const auto& c = a;
Scalar<int> d = static_cast<Scalar<int>>(c); // fails

这是编译错误(可以在这里检查 http://rextester.com/GOPYU13091 ),知道这里可能是什么问题吗?

source_file.cpp: In function ‘int main()’:
source_file.cpp:31:47: error: no matching function for call to ‘Scalar(const Scalar<double>&)’
Scalar<int> d = static_cast<Scalar<int>>(c);
^
source_file.cpp:12:3: note: candidate: Scalar<T>::Scalar(const Scalar<T>&) [with T = int] <near match>
Scalar(const Scalar& other) = default;
^
source_file.cpp:12:3: note: conversion of argument 1 would be ill-formed:
source_file.cpp:31:47: error: could not convert ‘c’ from ‘const Scalar<double>’ to ‘const Scalar<int>&’
Scalar<int> d = static_cast<Scalar<int>>(c);
^
source_file.cpp:10:3: note: candidate: Scalar<T>::Scalar(Scalar<T>&&) [with T = int] <near match>
Scalar(Scalar&& other) = default;
^
source_file.cpp:10:3: note: conversion of argument 1 would be ill-formed:
source_file.cpp:31:47: error: could not convert ‘c’ from ‘const Scalar<double>’ to ‘Scalar<int>&&’
Scalar<int> d = static_cast<Scalar<int>>(c);
^

最佳答案

这是一个 const 与非 const 的问题,而不是引用与对象的问题。

使用

auto& c = a;
Scalar<int> d = static_cast<Scalar<int>>(c);

对我有用。

通过将用户定义的转换运算符更改为const 成员函数

template <typename U>
explicit operator Scalar<U>() const {
return Scalar<U>{static_cast<U>(this->value)};
}

还确保以下工作正常。

const auto& c = a;
Scalar<int> d = static_cast<Scalar<int>>(c);

关于c++ - 用户定义的转换运算符不适用于引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42819714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com