gpt4 book ai didi

c++ - 初始化 C 数组的引用成员不要在 visual studio 2015 上编译

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

当我尝试在 g++ 上编译下面的代码时,它可以工作,但在 vs2015 上它失败并显示消息:错误 C2440:“正在初始化”:无法从“const bool *”转换为“const bool (&)[3]”

#include <iostream>

enum class Direction
{
RIGTH,
LEFT
};

struct Buffer
{
int catRigth = 4;
int catLeft = 8;
bool dogRigth[3] = {true, false, true};
bool dogLeft[3] = {false, true, false};
};

struct Bind
{
const int &cat;
const bool (&dog)[3];
Bind(const Buffer &buf, Direction direction) :
cat(direction == Direction::RIGTH ? buf.catRigth : buf.catLeft),
dog(direction == Direction::RIGTH ? buf.dogRigth : buf.dogLeft)
{
}
};

int main(int argc, char* argv[])
{

const Buffer buff;

Bind bindRigth(buff, Direction::RIGTH);
Bind bindLeft(buff, Direction::LEFT);

int catRigth = bindRigth.cat;
int catLeft = bindLeft.cat;

std::cout << catRigth << " " << catLeft;
}

它是标准的 C++ 代码还是 gcc 特定的行为?

最佳答案

MSVC 不应该将其类型衰减为 const bool *:

5.16.4 If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value category and it is a bit-field if the second or the third operand is a bit-field, or if both are bit-fields.

MSVC 的解决方法可能是:

#include <utility>

const struct A {
bool a[3] = {false};
} obj;

template <class Lhs, class Rhs>
auto &&Conditional(const bool x, Lhs &&lhs, Rhs &&rhs) {
if (x)
return std::forward<Lhs>(lhs);
return std::forward<Rhs>(rhs);
}

int main(int argc, char* argv[]) {
const bool (&t)[3] = Conditional(true, obj.a, obj.a);
return 0;
}

PS: Conditional 不是 constexpr 函数。

或者:const bool (&t)[3] = *(true ? &obj.a : &obj.a);

关于c++ - 初始化 C 数组的引用成员不要在 visual studio 2015 上编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53445018/

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