【问题标题】:Why constexpr implicit conversion doesn't always work?为什么 constexpr 隐式转换并不总是有效?
【发布时间】:2017-04-14 05:46:52
【问题描述】:
#include <iostream>

struct Index {
    constexpr operator int() const { return 666; }
};

template <int i> void foo() {
    std::cout << i << std::endl;
}

void wrapper(Index index) {
    foo<index>();
}

int main() {
    Index index;
//    foo<index>(); // error: the value of ‘index’ is not usable in a constant expression
    wrapper(index);
}

大家好。

我正在使用 constexpr 将变量“index”转换为 int 值,该值被替换为“foo”模板函数。 如果我直接从“main”调用foo&lt;index&gt;(),我会得到一个编译器错误。 如果从“包装器”执行相同的调用,那么一切都可以编译并正常工作。

我错过了什么?

使用 g++ (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6) 编译命令:g++ -std=c++14 main.tex

【问题讨论】:

  • 我认为这是 gcc 中的一个错误。 Clang 似乎同时接受:coliru.stacked-crooked.com/a/5f8b60e1f2dea54d
  • 谢谢,我没想到这个方向
  • 而且 gcc 6.3 也接受它Demo
  • 如果我将代码更改为“foo();”在 main 中,然后它通过编译。看来编译器对函数体中声明的函数参数和变量的处理方式不同。
  • 这是您的编译器的问题。最新版本的gccclangmsvc 都可以轻松编译您的代码。

标签: c++ casting g++


【解决方案1】:

报告了一个非常相似的错误here。它首先在 GCC 4.9.0 中被报道

在提供的分析中:

这是一个 GCC 错误。 GCC 处理指针类型的内部链接非类型模板参数的方式似乎有些混乱。

问题已经解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 2019-08-02
    • 2016-11-11
    相关资源
    最近更新 更多