c – 如何在编译时将C字符串转换为int?

前端之家收集整理的这篇文章主要介绍了c – 如何在编译时将C字符串转换为int?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望能够传递一个整数或一个double(或一个字符串)作为模板参数,并在某些情况下将结果转换为整数,并将其用作类中类型的模板参数.

这是我尝试过的:

@H_301_4@template <typename MPLString> class A { // the following works fine int fun() { // this function should return the int in the boost mpl type passed to it // (e.g. it might be of the form "123") return std::stoi(boost::mpl::c_str<MPLString>::value); } // the following breaks because std::stoi is not constexpr std::array<int,std::stoi(boost::mpl::c_str<MPLString>::value)> arr; };

我能以某种方式这样做吗?我已经尝试过std :: stoi和atoi,但两者都没有constexpr …任何想法如何做到这一点(我无法更改模板参数直接取一个int,因为它可能是一个双倍).

解决方法

使用常规C字符串定义constexpr stoi并不太难.它可以定义如下: @H_301_4@constexpr bool is_digit(char c) { return c <= '9' && c >= '0'; } constexpr int stoi_impl(const char* str,int value = 0) { return *str ? is_digit(*str) ? stoi_impl(str + 1,(*str - '0') + value * 10) : throw "compile-time-error: not a digit" : value; } constexpr int stoi(const char* str) { return stoi_impl(str); } int main() { static_assert(stoi("10") == 10,"..."); }

当在常量表达式中使用时,throw表达式无效,因此它将触发编译时错误而不是实际抛出.

猜你在找的C&C++相关文章