将编译时已知的函数参数转换为std::integral_constant的有效方法
Efficient way to convert a compile time known function argument to a std::integral_constant
昨天我读了一篇博客文章关于将编译时已知的函数参数从constexpr函数转换为类似std::integral_constant<>
的类型。
一个可能的用法示例是从用户定义的字面值转换类型。
考虑下面的例子:
constexpr auto convert(int i)
{
return std::integral_constant<int, i>{};
}
void test()
{
// should be std::integral_constant<int, 22>
using type = decltype(convert(22));
}
但是很明显Clang抛出了以下错误:
error: ‘i’ is not a constant expression
return std::integral_constant<int, i>{};
^
上述博客的作者建议使用模板化的用户定义文字进行分割将数字转换为std::integer_sequence,解析为int型。
但是这个建议似乎对我没用。
是否有一种有效的方法将编译时已知的函数参数转换为像std::integral_constant<>
这样的类型?
函数参数永远不能是编译时常量。虽然在我看来这是constexpr
的一个设计缺陷,但它就是这样。
可能有其他方法可以做到你想要的(宏,模板),但你不能用函数参数。
你需要使用一个模板:
template <int i>
constexpr auto convert()
{
return std::integral_constant<int, i>();
}
void test()
{
// should be std::integral_constant<int, 22>
using type = decltype(convert<22>());
}
或者(更好的)你可以使用模板别名:
template <int i> using convert = std::integral_constant<int, i>;
void test()
{
// should be std::integral_constant<int, 22>
using type = convert<22>;
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- 为什么 std::atomic<integral> 专用化不提供乘法和除法赋值运算符?