【发布时间】:2017-04-27 13:34:48
【问题描述】:
我刚遇到 gcc 和 clang 的编译错误,所以我认为这段代码是不可能的:
template < typename T >
struct Type {
using type = T;
};
template < int size = 1024 >
struct Foo {};
constexpr auto test_ = [] (const int size) {
return Type<Foo<size>>;
};
编译错误:
test.cpp:12:19: error: non-type template argument is not a constant expression
return Type<Foo<size>>;
^
1 error generated.
问题是为什么? size 是一个 const 值,应该可以作为模板参数使用,不是吗?我已经使用了一些静态常量值作为模板参数,但似乎不支持这种情况。
【问题讨论】:
-
问题在于
size不是编译时值,您可能会使用来自命令行参数的值调用该 lambda。 -
如果一个变量是
const,它并不一定意味着它在编译时是已知的(正如模板参数所需要的那样)。想象一下这样的例子:int a; std::cin >> a; const int b = a;。b是const,但它的值在编译时是未知的。
标签: c++ templates metaprogramming template-meta-programming