更新:私は以下に自分の答えを投稿 しましたそしてこの問題のより長いバージョンがここにあります:http ://scrupulousabstractions.tumblr.com/post/38460349771/c-11-type-safe-use-of-integer-user-defined-リテラル
質問:
値をunsignedlonglongとして取得する単純なconstexpr
ユーザー定義リテラルを作成しました(これが、ユーザー定義の数値リテラルの動作方法です:http: //en.cppreference.com/w/cpp/language/user_literal)。値がsignedlonglongに収まるようにしてください。_X
それはすべてうまく機能します(値が大きすぎるとコンパイルエラーが発生します)が、次のような変数を明示的に作成した場合に限ります
constexpr auto a= 150_X;
代わりに私が次のような典型的なものを書く場合
cout << 150_X << endl;;
テストはコンパイル時に実行されません。
constexpr関数は、constexpr変数に割り当てられている場合にのみ、コンパイル時に実行されますか?(私はそれを標準で見つけることができませんでした)
_X
私が探しているものの安全な行動を達成することは可能ですか?
完全な例:
#include<iostream>
#include<stdexcept>
inline constexpr long long testConv(unsigned long long v) {
return (v > 100 ) ? throw std::exception() : v;
} // will eventually use actual limit from numeric_limits
inline constexpr long long operator "" _X(unsigned long long f) {
return testConv(f) ;
}
int main(){
constexpr auto a= 5_X;
std::cout << a << std::endl;
std::cout << 200_X << std::endl; // This bad literal is accepted at compile time
constexpr auto c=250_X; // This bad literal is not accepted at compile time
std::cout << c << std::endl;
}
ああ、参考までに:私はgcc4.7.2を使用しました。