const 值作为模板参数 [英] const value as template parameter
问题描述
我刚刚遇到了 gcc 和 clang 的编译错误,所以我认为这段代码是不可能的:
I just run into a compile error from both gcc and clang, so I assume this code is not possible :
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
是一个常量值,应该能够适合作为模板参数吗?我已经使用了一些静态常量值作为模板参数,但似乎不支持这种情况.
The question is why? size
is a const value and should be able to fit as a template parameter no? I already used some static const value as template parameter, but seems this case is not supported.
推荐答案
size
是一个常量值,应该能够适合作为模板参数吗?
size
is a const value and should be able to fit as a template parameter no?
不,const
值在编译时不一定知道(即它们不是常量表达式).
No, const
values are not necessarily known at compile-time (i.e. they're not constant expressions).
你想要的是std::integral_constant
一个>:
What you want is std::integral_constant
:
constexpr auto test_ = [] (auto size)
{
return Type<Foo<size>>{};
};
test_(std::integral_constant<int, 100>{});
<小时>
正如评论中提到的 Rakete1111,return Type
也是格式错误的 - 您可能想像我上面那样实例化它.
As Rakete1111 mentioned in the comments, the line return Type<Foo<size>>;
is also ill-formed - you probably wanted to instantiate it as I did above.
这篇关于const 值作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!