0
我們假設我想寫返回指針非空容器的第一個元素的函數。當模板返回類型阻止它實例化時,如何給用戶提供很好的static_assert消息?
// REQUIRES: c not empty
template<typename C>
auto pointer_to_first(C& c) -> decltype(&(*c.begin())){
return nullptr; // TODO: implement
}
如果我嘗試使用vector<bool>
vector<bool> vb{false, false, true};
pointer_to_first(vb);
編譯器使用此給出錯誤信息混淆初學者:
error: taking address of temporary [-fpermissive] auto pointer_to_first(C& c) -> decltype(&(*c.begin())){
因爲初學者不知道代理這是令人困惑的是vector<bool>
用途而vb
不是臨時的。
所以我要補充static_assert
s表示容器不能vector<bool>
,也該容器必須有begin()
,end()
... 我知道該怎麼做,但問題是,由於重載解析發生故障,用戶將只能看到編譯器錯誤消息。
有沒有辦法解決這個問題?