【问题标题】:consteval with templates possible? [duplicate]可以使用模板进行 consteval 吗? [复制]
【发布时间】:2021-09-13 17:02:54
【问题描述】:

我正在尝试制作一些 consteval 函数的模板版本,我不清楚这里是否有任何限制。

template <typename T>
consteval T max(const T& a, const T& b) {
    return (a > b) ? a : b;
}

template <typename T>
consteval T mid(const T& a, const T& b, const T& c) {
    T m = max(max(a, b), c);

    if (m == a)
        return max(b, c);
    if (m == b)
        return max(a, c);

    return max(a, b);
}

consteval int imax(const int& a, const int& b) {
    return (a > b) ? a : b;
}

consteval int imid(const int& a, const int& b, const int& c) {
    int m = imax(max(a, b), c);

    if (m == a)
        return imax(b, c);
    if (m == b)
        return imax(a, c);

    return imax(a, b);
}

大多数情况下都可以正常工作 -

std::cout << imax(1,2) << std::endl;
std::cout << imid(1,2,3) << std::endl;
std::cout << max(1,2) << std::endl;       // templated version works fine

我再次看到依赖于 consteval 函数的模板版本的编译错误。具体来说,这个用例无法编译

std::cout << mid(1,2,3) << std::endl;     // templated version fails to compile

错误-

FAILED: out.p/main.cpp.o                                                                                                                                                                                   
clang++-12 -Iout.p -I. -I.. -fcolor-diagnostics -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -Wnon-virtual-dtor -Wextra -Wpedantic -std=c++2a -O0 -g -MD -MQ out.p/main.cpp.o -MF out.p/main.cpp.o.d -o out.p
/main.cpp.o -c ../main.cpp                                                                                                                                                                                 
../main.cpp:11:11: error: call to consteval function 'max<int>' is not a constant expression                                                                                                               
    T m = max(max(a, b), c);

【问题讨论】:

  • 这可能是一个clang错误。代码看起来不错,gcc 没问题godbolt.org/z/aP1e5Ks5P
  • @cigien 也许是回归。 Clang 10.0.1 accepts it
  • 啊,没想到这可能是编译器问题。感谢您指出。是的,确实看起来是一种回归。编译器资源管理器工具似乎很有帮助。 @cigien,您可以将其更新为我接受它的答案。
  • @TedLyngmo 可能。在某些时候,clang 解析了 consteval,但只是忽略了它(或将其视为 constexpr),因此需要考虑这一点。

标签: c++ c++20


【解决方案1】:

正如@cigien 所指出的,这确实是一个clang 错误。它适用于 gcc。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2013-01-24
    • 2010-11-25
    相关资源
    最近更新 更多