将编译时已知函数参数转换为std :: integral_constant的有效方法 [英] Efficient way to convert a compile time known function argument to a std::integral_constant

查看:515
本文介绍了将编译时已知函数参数转换为std :: integral_constant的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我阅读了博客条目
关于将编译时已知的函数参数从constexpr函数转换为 std :: integral_constant<> 之类的类型。

Yesterday I read a blog entry about converting a compile time known function argument from a constexpr function to a type like std::integral_constant<>.

一个可能的用法示例是从用户定义的文字转换类型。

A possible usage example is to convert types from user defined literals.

请考虑以下示例:

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会引发以下错误:

But obviously and as expected Clang throws the following error:


错误:'i'不是常量表达式
return std :: integral_constant< int,i> {};
^

上述博客的作者建议使用模板化的用户定义文字来拆分
将数字转换为std :: integer_sequence并将其解析为一个整数。

The Author of the mentioned blog proposed to use a templated user defined literal to split the number into a std::integer_sequence to parse it into an int.

但是这个建议对我来说似乎不可用。

But this suggestion seems not useable for me.

是否有一种有效的方法将编译时已知的函数参数转换为类似 std :: integral_constant<> 的类型?

Is there an efficient way to convert a compile time known function argument into a type like std::integral_constant<>?

推荐答案

函数自变量不能从不是编译时常量。虽然我认为这是 constexpr 的设计缺陷,但事实就是这样。

Function arguments can never be compile-time constants. While this is a design flaw of constexpr in my opinion, it is the way it is.

可能其他方法来执行所需的操作(宏,模板),但不能使用函数参数来完成。

There might be other ways to do what you want (macros, templates), but you can not do it with function arguments.

这篇关于将编译时已知函数参数转换为std :: integral_constant的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆