【发布时间】:2014-08-08 02:20:31
【问题描述】:
我希望能够将整数或双精度(或字符串)作为模板参数传递并且在某些情况下将结果转换为整数并将其用作模板参数输入类。
这是我尝试过的:
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,如它可能是双倍的)。
【问题讨论】:
-
你的标题是双精度,你的代码是整数。哪一个?一个比另一个更难。查看代码,我什至不确定您希望它如何工作。
-
我记得我在某个地方看到过
atoi的 constexpr 实现 -
std::array有两个模板参数,typename T和size_t N。你想要哪一个?因为double只会从size_t截断。您是否只想检测字符串是否可以是int或double? -
在 C++14 中,这些
constexpr函数变得更加琐碎。您几乎可以实现一个幼稚的atoi并将其标记为constexpr。 -
看看这里:enki-tech.blogspot.ca/2012/09/…,作者定义(除其他外)一个 constexpr
atoi。我还记得在 SO 上看到过类似的问题,但再也找不到了。我在这里找到了编译时itoa:stackoverflow.com/q/6713420/3093378