【发布时间】: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<index>(),我会得到一个编译器错误。
如果从“包装器”执行相同的调用,那么一切都可以编译并正常工作。
我错过了什么?
使用 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 中,然后它通过编译。看来编译器对函数体中声明的函数参数和变量的处理方式不同。