【问题标题】:constexpr discrepancy between gcc8.2 and (intel) icc19.0.1gcc8.2和(intel)icc19.0.1之间的constexpr差异
【发布时间】:2019-06-22 18:22:06
【问题描述】:

以下代码在 gcc 8.2 上编译,但在 icc 19.0.1 上编译失败:

#include <tuple>

template <typename Type, typename... TypeList>
constexpr size_t f(std::tuple<TypeList...> const &){
    return 0;
}

template <typename Type, typename Tuple>
size_t g(Tuple && t){
    static size_t constexpr v= f<Type>(t);
    return v;
}

size_t h(){
    std::tuple<int> tuple;
    return g<int>(tuple);
}

我从 icc 收到的错误是:

error: expression must have a constant value
static size_t constexpr v = f<Type>(t);
                            ^
note: the value of parameter "t" cannot be used as a constant

英特尔的编译器是正确的,因为“t”通常是未知的,不能用作常量。但是,仅使用在编译时已知的“t”类型(定义模板参数包“TypeList”)。

为什么在 gcc 中允许但在 icc 中不允许?哪个编译器是正确的?

【问题讨论】:

  • clangmsvc 也拒绝此代码。

标签: c++ gcc compiler-errors metaprogramming icc


【解决方案1】:

这并不能回答我关于谁是正确的以及为什么正确的问题,但这里有一个(稍微不那么优雅)的解决方法,它适用于两个编译器。如果有人知道更好的解决方案,我会很高兴。

template <typename Type, typename Tuple, size_t... Indices>
constexpr size_t f(std::index_sequence<Indices...> const &){
    // TypeList is now 'std::tuple_element_t<Indices, TTuple>...'
    return 0;
}
template <typename Type, typename Tuple>
constexpr size_t f(){
    using BareTuple = std::remove_const_t<std::remove_reference_t<Tuple> >;
    return f<Type, BareTuple>
        (std::make_index_sequence<std::tuple_size_v<BareTuple>>{});
}
template <typename Type, typename Tuple>
constexpr size_t g(Tuple && t){
    size_t constexpr occurrences = f<Type, Tuple>();
    return occurrences;
}
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    • 2010-10-19
    • 2020-09-15
    • 2014-06-30
    • 2011-11-16
    • 2011-05-08
    相关资源
    最近更新 更多