我希望能够传递一个整数或一个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; };
我能以某种方式这样做吗?我已经尝试过std :: stoi和atoi,但两者都没有constexpr …任何想法如何做到这一点(我无法更改模板参数直接取一个int,因为它可能是一个双倍).
解决方法
使用常规C字符串定义constexpr stoi并不太难.它可以定义如下:
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表达式无效,因此它将触发编译时错误而不是实际抛出.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。