我刚刚遇到了 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 值,应该能够适合作为模板参数,不是吗?我已经使用了一些静态 const 值作为模板参数,但似乎不支持这种情况。
最佳答案
size
is a const value and should be able to fit as a template parameter no?
不,const
值不一定在编译时已知(即它们不是常量表达式)。
你想要的是 std::integral_constant
:
constexpr auto test_ = [] (auto size)
{
return Type<Foo<size>>{};
};
test_(std::integral_constant<int, 100>{});
如Rakete1111评论中提到,行 return Type<Foo<size>>;
也是格式错误的 - 您可能想像我上面那样实例化它。
关于c++ - const 值作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43659475/