2013-11-01 56 views
3

讓我們嘗試創建一個類似指針的類型,該類型與RandomAccessIteratorNullablePointer概念都匹配。 這裏的目標是創建一個自定義的Allocator 爲了使用std :: vector與我們的指針類型。你可以發現片斷herestd :: vector的概念和GCC實現

試圖編譯這段代碼時,問題出現了:

int main() 
{ 
    std::vector<float, allocator<float>> t {0.f, 0.f}; 
} 

我們得到以下錯誤信息:

/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/stl_vector.h:173:6: error: 
    value of type 'pointer' (aka 'ptr_like<int>') is not contextually convertible 
    to 'bool' 
    if (__p) 

這裏我們可以看到,我們的類型必須爲布爾兌換。這並不難, ,如果人們有我們的指針類型的實例,他們可能會像這樣使用它。 因此,讓我們做到這一點,取消以下我們的代碼片段:

// In detail::ptr_like we add : 
operator bool() const; 

,我們得到以下錯誤鏗鏘:

/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/stl_vector.h:168:25: error: 
    conditional expression is ambiguous; 'pointer' (aka 'ptr_like<int>') can be 
    converted to 'int' and vice versa 
    { return __n != 0 ? _M_impl.allocate(__n) : 0; } 

鏘的錯誤告訴我們究竟爲什麼我們陷入困境這裏。 現在,我已經找到了唯一可行的解​​決方案如下:

  • 與C++ 11關鍵字nullptr更換0當C++ 11請求
  • 通過澆鑄更換0指針類型static_cast<pointer>(0)
  • 在分配器概念中更新指針的概念要求。
  • 沒有使用構造與std::initializer_list(SAD)

這是錯誤的定義在C++中的自定義指針?

這是一個錯誤?

+4

使你的操作符布爾明確。 HTTP://克里斯 - 夏普。blogspot.co.uk/2013/07/contextually-converted-to-bool.html – BoBTFish

+0

@BoBTFish嗯,我現在感覺很蠢。非常感謝 ! – Nemikolh

回答

4

擴大我的評論。

{ return __n != 0 ? _M_impl.allocate(__n) : 0; } 

第一個結果可以轉換爲boolint。第二個結果可以轉換爲int。這與將第二個結果轉換爲pointer的結果一樣好,因此它是不明確的。

但我們不希望bool轉換在這裏可用,所以我們可以使它explicit。它仍然可用於邏輯條件等,正如我描述的here。 正在內部轉換爲bool是另一個條件標準放置在滿足NullablePointer要求的自定義指針類型上(自2011年起 - 見17.6.3.3/3)。

2

我建議將轉換運算符定義爲顯式。例如

explicit operator bool() const;