如何在编译时将C字符串转换为int? [英] How do I convert a C string to a int at compile time?

查看:108
本文介绍了如何在编译时将C字符串转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够传递整数或双精度(或字符串)作为模板参数在某些情况下将结果转换为整数,并将其用作模板参数

I want to be able to pass an integer or a double (or a string) as a template argument and in some instances convert the result to an integer and use it as a template argument for a type in the class.

这是我尝试过的内容:

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 的任何想法)

Can I do this somehow? I've tried std::stoi and atoi but neither are constexpr... Any ideas how this could be done (I cannot change the template parameter to take an int directly, as it might be a double).

推荐答案

定义 constexpr stoi 不太合适使用常规C字符串很难。可以定义如下:

Defining a constexpr stoi isn't too hard with regular C strings. It can be defined as follows:

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表达式无效时,它将触发一个编译时错误,而不是实际抛出。

The throw expression is invalid when used in constant expressions so it'll trigger a compile time error rather than actually throwing.

这篇关于如何在编译时将C字符串转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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