更新:我下面貼 我自己的答案,並有此事更長的版本在這裏:http://scrupulousabstractions.tumblr.com/post/38460349771/c-11-type-safe-use-of-integer-user-defined-literals編譯時類型轉換檢查(constexpr和用戶定義的文字)
問:
我我做了一個簡單的constexpr
用戶定義文字_X
,它獲得了一個無符號長long值(這就是數字用戶定義的文字的工作方式:http://en.cppreference.com/w/cpp/language/user_literal),然後我確定該值符合簽名long long。
這一切運作良好(過大的值會導致編譯錯誤),但只有當我明確地創建一個變量如
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。
很好的答案,並且感謝您的延長寫作!很有幫助。 – U007D
這當然只有在文字不是八進制或十六進制時纔有效。在這些情況下,將需要不同的文字分析器。 – nshct