gpt4 book ai didi

c++ - 与三元运算不兼容的操作数

转载 作者:搜寻专家 更新时间:2023-10-31 02:06:52 26 4
gpt4 key购买 nike

我在编写 lambda 表达式时偶然发现了一个奇怪的问题。这是代码:

#if 1 /* exhibit A */
const auto giveup = this->__randomGiveUp();
auto evtFunc = [this, giveup]() {
this->__acquireLock();
if (giveup) {
this->__releaseLock();
}
};
#endif
#if 0 /* exhibit B */
auto evtFunc = this->__randomGiveUp() ? (std::function<void()>)[this]() {
this->__acquireLock();
this->__releaseLock();
} : [this]() {
this->__acquireLock();
};
#endif
#if 0 /* exhibit C */
auto evtFunc = this->__randomGiveUp() ? [this]() {
this->__acquireLock();
this->__releaseLock();
} : [this]() {
this->__acquireLock();
};
#endif
#if 0 /* exhibit D */
std::function<void()> evtFunc = this->__randomGiveUp() ? [this]() {
this->__acquireLock();
this->__releaseLock();
} : [this]() {
this->__acquireLock();
};
#endif

this->__eventCtx.addEvent(this->__tickStart + this->__randomAcquireDelay(), evtFunc);

我认为可行的原始代码是 C。他们基本上都做同样的事情。 GCC 和 Clang(Atom 的 linter 使用)产生:

  • 什么有效:A,B
  • 什么不是:C、D

表示操作数不是同一类型。这对我来说很奇怪。我的假设是每个 lambda 表达式都被赋予了一个唯一的类型,但这并不能解释有效的展览 B。为什么 D 不工作而 B 工作?是否只是编译器在确定 lambda 类型时胡乱猜测?

所以,我的问题是:

  • 为什么 B 工作???
  • 是否每个 lambda 表达式都有自己独特的类型并需要强制转换(话又说回来,B 是怎么工作的??)?
  • 这是一个错误吗?

需要说明的是,this->__randomGiveUp() 的返回类型是 bool。

最佳答案

每个 lambda 函数都有自己独特的类型。这就是 C 和 D 不起作用的原因:第二个和第三个操作数之间没有转换。 C++ 不会尝试转换为一些不相关的类型,例如 std::function如果两个操作数都不是该类型。

这就解释了 B 起作用的原因:第二个运算符的类型是 std::function<>第三个操作数的 lambda 函数类型可以通过 std::function 转换为第二个操作数的类型构造函数。

关于c++ - 与三元运算不兼容的操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49596776/

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