この質問はこのために尋ねられています。
C ++ 11では、数値リテラルに対して次のようなリテラルを定義できます。
template<char...> OutputType operator "" _suffix();
つまり503_suffix
、<'5','0','3'>
これは素晴らしいですが、それが入っている形ではあまり役に立ちません。
これを数値タイプに戻すにはどうすればよいですか?これはに変わり<'5','0','3'>
ますconstexpr
503
。さらに、浮動小数点リテラルでも機能する必要があります。または<'5','.','3>
になりますint 5
float 5.3
前の質問で部分的な解決策が見つかりましたが、整数以外では機能しません。
template <typename t>
constexpr t pow(t base, int exp) {
return (exp > 0) ? base * pow(base, exp-1) : 1;
};
template <char...> struct literal;
template <> struct literal<> {
static const unsigned int to_int = 0;
};
template <char c, char ...cv> struct literal<c, cv...> {
static const unsigned int to_int = (c - '0') * pow(10, sizeof...(cv)) + literal<cv...>::to_int;
};
// use: literal<...>::to_int
// literal<'1','.','5'>::to_int doesn't work
// literal<'1','.','5'>::to_float not implemented