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

qua*_*ant 6 c++ boost-mpl c++11

我希望能够传递一个整数或一个double(或一个字符串)作为模板参数,在某些情况下将结果转换为整数,并将其用作类中类型的模板参数.

这是我尝试过的:

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;
};
Run Code Online (Sandbox Code Playgroud)

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

Rap*_*ptz 14

constexpr stoi使用常规C字符串定义a 并不太难.它可以定义如下:

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, "...");
}
Run Code Online (Sandbox Code Playgroud)

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

  • @ikh“常量表达式”中只允许某些内容。如果您在“常量表达式”上下文中使用“constexpr”函数并且出现不允许的事情之一,则编译器将无法编译它。 (2认同)