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.
Here's what I've tried:
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;
};
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).
atoi
somewhere is this site – Sterilizestd::array
has two template parameters,typename T
andsize_t N
. Which one do you want? Becausedouble
will just truncate fromsize_t
. Do you want to just detect if the string can be anint
ordouble
? – Lewendalconstexpr
functions become a lot more trivial. You could pretty much implement a naiveatoi
and mark itconstexpr
. – Pilotatoi
. I also remembered to have seen a similar question on SO, but cannot find it anymore. I found the compile-timeitoa
here though: https://mcmap.net/q/523680/-c-convert-integer-to-string-at-compile-time/3093378 – Mmeboost::mpl
toint
at compile time. – Pyroelectricboost::mpl
. – Lewendalboost::mpl::c_str<MPLString>::value
is aconstexpr
of typechar*
– Pyroelectric