gpt4 book ai didi

c++ - 当 GCC 正常时 Clang 报告 "constexpr if condition is not a constant expression"

转载 作者:行者123 更新时间:2023-12-01 13:42:35 31 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Static member access in constant expressions

(2 个回答)


去年关闭。




我在 x64 Linux 上使用 clang 9.0.1 和 gcc 9.2.1,两者都带有 --std=c++17 (或 --std=c++2a)。

gcc 可以在没有任何错误或警告的情况下构建以下示例,而 clang++ 报告 error: constexpr if condition is not a constant expression在两个 if constexpr线。 (顺便说一句,在我的 MacBook 上,Apple clang-11.0.0 也报告了同样的错误。)

MCVE:

#include <utility>

enum class TopicType {
MarketData = 'M',
Timer = 'T',
};

template<class Topic>
struct TopicBase {
constexpr static TopicType type() { return Topic::type; };
const Topic& topicImp;
explicit TopicBase(const Topic &t) : topicImp(t) {}
};

struct MarketDataTopic {
static constexpr TopicType type{TopicType::MarketData};
};

struct TimerTopic {
static constexpr TopicType type{TopicType::Timer};
};

template<class Topic>
int subscribe(TopicBase<Topic>&& topic) {

if constexpr (topic.type() == TopicType::MarketData) { // <-- clang++ reports error here
return 1;
}
if constexpr (topic.type() == TopicType::Timer) { // and error here
return 2;
}

return -1;
}

int main(int argc, const char **argv) {

MarketDataTopic m{};
TimerTopic t{};

TopicBase<MarketDataTopic> b1{m};
TopicBase<TimerTopic> b2{t};

subscribe(std::move(b1));


return 0;
}

在线编译器 https://godbolt.org/z/rARi_N有相同的结果。

那么哪个编译器是正确的呢?如果它是一个错误,如何修复它的 clang ?

最佳答案

好吧,您可以这样做以使其适用于 clang:

template<class Topic>
int subscribe(TopicBase<Topic>&& topic) {
using myType = TopicBase<Topic>;
if constexpr (myType::type() == TopicType::MarketData) { // <-- clang++ reports error here
return 1;
}
if constexpr (myType::type() == TopicType::Timer) { // and error here
return 2;
}

return -1;
}

Run live

很可能这是clang中的一个错误。最好举报。

关于c++ - 当 GCC 正常时 Clang 报告 "constexpr if condition is not a constant expression",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60558347/

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