有可能使用模板吗? [英] consteval with templates possible?

查看:30
本文介绍了有可能使用模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一些模板版本的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);

推荐答案

正如@cigien所指出的,这确实是一个clang bug。它和GCC相处得很好。

这篇关于有可能使用模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆