Mat*_*vel 2 c++ templates metaprogramming template-meta-programming
我刚刚遇到了 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>>;
};
Run Code Online (Sandbox Code Playgroud)
编译错误:
test.cpp:12:19: error: non-type template argument is not a constant expression
return Type<Foo<size>>;
^
1 error generated.
Run Code Online (Sandbox Code Playgroud)
问题是为什么?size是一个常量值,应该能够适合作为模板参数不是吗?我已经使用了一些静态常量值作为模板参数,但似乎不支持这种情况。
size是一个常量值,应该能够适合作为模板参数不是吗?
不,const在编译时不一定知道值(即它们不是常量表达式)。
你想要的是std::integral_constant:
constexpr auto test_ = [] (auto size)
{
return Type<Foo<size>>{};
};
test_(std::integral_constant<int, 100>{});
Run Code Online (Sandbox Code Playgroud)
正如评论中提到的Rakete1111,该行return Type<Foo<size>>;也是格式错误的- 您可能想像我上面所做的那样实例化它。