const 值作为模板参数
const value as template parameter
我刚刚 运行 进入 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
is a const value and should be able to fit as a template parameter no?
不,const
值在编译时不一定已知 (即它们不是 常量表达式) .
constexpr auto test_ = [] (auto size)
{
return Type<Foo<size>>{};
};
test_(std::integral_constant<int, 100>{});
正如评论中提到的 Rakete1111,行 return Type<Foo<size>>;
也是错误的——您可能想像我上面那样实例化它。
我刚刚 运行 进入 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
is a const value and should be able to fit as a template parameter no?
不,const
值在编译时不一定已知 (即它们不是 常量表达式) .
constexpr auto test_ = [] (auto size)
{
return Type<Foo<size>>{};
};
test_(std::integral_constant<int, 100>{});
正如评论中提到的 Rakete1111,行 return Type<Foo<size>>;
也是错误的——您可能想像我上面那样实例化它。