gpt4 book ai didi

C++ - 在保持灵活代码的同时处理隐式/显式转换

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:06:30 27 4
gpt4 key购买 nike

我正在寻找一种方法来表达类 A 和内置整数类型之间的互操作性,同时在我的代码中保持高度灵 active 。例如,我希望能够在 (AA) 之间自由使用 operator &,(Aint), (int and A) and (int and int) ,即我想得到 x = y & z 的结果,无论 xyz 是类型class Aint 类型,只写:

x = y & z;

以下代码有效:

#include <cstdlib>
#include <iostream>

class A {
public:
int x;

explicit A(int i) : x(i) {}

operator int() {
return this->x;
}

A operator &(const A& src) const {
return A(this->x & src.x);
}

};

int main() {
int b(2), b2(0), b3(0);
A a(3);

b2 = a & b;
b3 = b & a;

std::cout << b2 << std::endl;
std::cout << b3 << std::endl;

return 0;
}

但是,如果我在 class A 中添加一个从 Aunsigned int 的新转换函数,这将不再起作用,因为 operator & 定义在 (intint) 以及 (intunsigned int 之间>),所以当我这样做时:

b2 = a & b

编译器不知道 a 是否应该转换为 intunsigned int,这是合乎逻辑的。我看到 2 种可能性来解决它:

  1. Aint 之间以及 intA 之间显式实现 operator & >。我不希望这样,因为添加与另一种类型的兼容性将需要重新实现需要支持的所有运算符的许多组合。
  2. 强制从内置类型隐式转换为A,因此AA 之间只有operator &是必需的。

对于灵 active 和可维护性,我认为解决方案 2 更好。所以我可以改为实现以下类 A:

class A {
public:
int x;

A(int i) : x(i) {}

A(unsigned int i) : x(i) {}

explicit operator int() {
return this->x;
}

explicit operator unsigned int() {
return static_cast<unsigned int>(this->x);
}

};

A operator &(const A& src1, const A& src2) {
return A(src1.x & src2.x);
}

现在,尽管从/到 int 和 unsigned int 的转换都已定义,我可以执行 whether (A and A), (Aint)、(intA) 和 (intint ).

但是我无法编译代码:

b2 = a & b;
b3 = b & a;

因为 b2b3int 和 (a & b ) (resp. (b & a)) 返回一个 A 并从 A 转换为 int 现在必须明确,我必须写:

b2 = static_cast<int>(a & b);
b3 = static_cast<int>(b & a);

我的问题(最后)是:

有没有办法编写 A 类,这样我就可以:

b2 = a & b;
b3 = b & a;

同时在 (AA) 之间只保留 operator & 的一个定义?从理论上讲,这可以通过重载 int 类的 operator =(const A&) 来完成,这在技术上是不可能的。

最佳答案

我认为 bipll 意味着使用独立的 operator& 函数:

#include <cstdlib>
#include <iostream>

using std::cout;
using std::endl;

class A
{
int x;
public:
explicit A(int i) : x{i}
{ }

explicit A(unsigned i) : x{static_cast<int>(i)}
{ }

operator int() const
{
return this->x;
}

operator unsigned() const
{
return static_cast<unsigned>(this->x);
}
};

A operator&(A const& lhs, A const& rhs)
{
return A(lhs.operator int() & rhs.operator int());
}

A operator&(A const& lhs, int rhs)
{
return A(lhs.operator int() & rhs);
}

A operator&(int lhs, A const& rhs)
{
return A(lhs & rhs.operator int());
}

A operator&(A const& lhs, unsigned rhs)
{
return A(lhs.operator unsigned() & rhs);
}

A operator&(unsigned lhs, A const& rhs)
{
return A(lhs & rhs.operator unsigned());
}

int main()
{
auto b = 2;
auto b2 = 0;
auto b3 = 0;
auto u = 2;
auto u4 = 0u;
auto u5 = 0u;
auto a = A{3};

b2 = a & b;
b3 = b & a;
u4 = a & u;
u5 = u & a;

cout << b2 << endl;
cout << b3 << endl;
cout << u4 << endl;
cout << u5 << endl;
}

关于C++ - 在保持灵活代码的同时处理隐式/显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49223881/

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