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
是一个const值,应该能够作为模板参数no?
no, 您想要的是 正如评论中提到的rakete1111所述, const
值不一定在Compile time 上知道(即。std::integral_constant
:constexpr auto test_ = [] (auto size)
{
return Type<Foo<size>>{};
};
test_(std::integral_constant<int, 100>{});
return Type<Foo<size>>;
行也不明显 - 您可能想像我上面一样对其进行实例化。
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 'HMODULE LoadLibraryA(LPCSTR)':无法将参数 1 从 'const _Elem *' 转换为 'LPCSTR'
- 将函数参数"const char*"转换为"std::string_view"是
- 将参数传递为"const"的奇怪效果
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- std::span<const T> 作为函数模板中的参数
- 视觉工作室 2017;启用 /permissive 时,类型 "const wchar_t *" 的参数与类型 "PWSTR" 的参数不兼容
- 何时应在构造函数参数中使用 const C++?
- 不允许运算符 const 参数调用 const 成员函数
- std::p ackaged_task 应该删除带有 const 参数的复制 c'tor
- 知道模板参数在编译时是否为 const char*?
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 具有参数 (const T *&) 或 (T * &) 或 (const T * const &) 或 (T * const &) 的方法
- 为什么在函数参数前面添加 const 会出错?
- 在函数中使用运算符重载,在 c++ 中使用 const 类型输入参数
- C++ Boost - 序列化错误 - 将"const B"作为"this"参数
- C++ 我应该如何解释函数参数long(*pPointer)(OtherClass *const, long)?
- 什么..表示函数内部参数(const char*值,..)
- 如果参数创建本地副本,则使用参数"const [variable_type] &"的目的是什么?
- 候选函数不可行:第一个参数('const Node *')将失去常量限定符