想象一下這個簡單的constexpr功能:
// Whatever, the exact values don't matter for this example
constexpr float items[100] = { 1.23f, 4.56f };
constexpr int length = 12;
constexpr float getItem(int index)
{
if (index < 0 || index >= length)
{
// ArrayIndexOutOfRangeException has a constructor that takes a const char* and one that takes a std::string.
throw ArrayIndexOutOfRangeException("You did a bad.");
}
return items[index];
}
你可以像這樣使用它:
int main()
{
constexpr float f1 = getItem( 0); std::cout << f1 << std::endl; // Works fine
constexpr float f2 = getItem( 1); std::cout << f2 << std::endl; // Works fine
constexpr float f3 = getItem(-1); std::cout << f3 << std::endl; // Does not compile: "constexpr variable 'f3' must be initialized by a constant expression", "subexpression not valid in a constant expression"
constexpr float f4 = getItem(20); std::cout << f4 << std::endl; // Does not compile: "constexpr variable 'f4' must be initialized by a constant expression", "subexpression not valid in a constant expression"
return 0;
}
偉大的!屁股重量!
volatile int i;
i = 123; // As a placeholder for something like this: std::cin >> i;
float f5 = getItem(i);
std::cout << f5 << std::endl;
這會在運行時拋出“在拋出 'ArrayIndexOutOfRangeException' 實體后呼叫終止”和“what(): You did a bad”。
好的,這不是很有幫助,我想創建一個更好的錯誤訊息:
constexpr float getItem(int index)
{
if (index < 0 || index >= length)
{
std::stringstream stream;
stream << "You did a bad. getItem was called with an invalid index (" << index << "), but it should have been non-negative and less than the total number of items (" << length << ").";
throw ArrayIndexOutOfRangeException(stream.str());
}
return items[index];
}
但這是不允許的:“不能在 constexpr 函式中定義非文字型別的變數 'std::stringstream'(又名 'basic_stringstream')”。
我可以為編譯時版本提供更簡單的錯誤訊息,并且只在運行時版本中進行復雜的字串操作。
又怎樣?
請注意,這是 C 17(一些 GCC 風格),它可能沒有 C 20 所具有的一些與 constexpr 相關的特性。
其他代碼要求函式保持不變constexpr。
如果可能的話,我想避免重復該功能。
uj5u.com熱心網友回復:
您可能會在另一個函式中創建錯誤訊息:
std::string get_error_message(int index, int length = 10)
{
std::stringstream stream;
stream << "You did a bad. getItem was called with an invalid index ("
<< index
<< "), but it should have been non-negative "
<< "and less than the total number of items ("
<< length << ").";
return stream.str();
}
constexpr float getItem(int index)
{
constexpr int length = 10;
constexpr std::array<float, length> items{};
if (index < 0 || index >= length)
{
throw std::runtime_error(get_error_message(index, length));
}
return items[index];
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/467509.html
