2017-08-11 32 views
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() ... 我知道該怎麼做,但問題是,由於重載解析發生故障,用戶將只能看到編譯器錯誤消息。

有沒有辦法解決這個問題?

回答

1

,直到我們有概念,你可以添加一個額外層,以允許有static_assert,避免SFINAE:

// Your SFINAE function: 
template<typename C> 
auto pointer_to_first_impl(C& c) -> decltype(&(*c.begin())){ 
    return nullptr;// TODO: implement 
} 

template<typename C> 
decltype(auto) pointer_to_first(C& c) 
{ 
    // You need to implement the traits for the check 
    static_assert(my_cond<C>::value, "type is incorrect"); 
    return pointer_to_first_impl(c); 
}