2012-09-20 19 views
8

作爲開發人員團隊的一員,我希望確保在我們發佈的自定義迭代器上實現一組函數(和運算符)。使用STL迭代器類型作爲基礎類型可以提供幫助,但是由於某些原因(不受我的控制),我們決定不強制執行STL兼容性。迭代器由同一個團隊和整個公司的人員使用。用於確保設計合同的static_assert

我想設計一個模板類,它使用迭代器類型並根據設計合同進行測試。

例如,我希望迭代器實現一個運算符++,運算符 - 並且還聲明所需的typedefs。

1>是否有可能實現這樣的模板類來執行設計合同?可能使用static_assert?

2>如果是的話,這是一個很好的設計嗎?

參考:custom iterator

+1

HTTP:也許吧?//www.boost.org/doc/libs/1_48_0/libs/type_traits/doc/html/boost_typetraits/category/value_traits/operators.html – BoBTFish

+1

[漂亮的打印機](http://stackoverflow.com/q/4850473/596781)有一個C++ 11特徵類來檢查一個類型是否有迭代器類型,以及'begin' /'end'函數是否返回該迭代器類型。 –

+0

@Kerrek謝謝你的例子。我節省了幾個人時間。 :) – Ram

回答

10

是否有可能實現這樣的模板類來執行設計合同?可能使用static_assert?

對於檢查具體方法是否存在(非常類似於this example):

struct Hello 
{ 
}; 

struct Generic { 
    int operator++() 
    { 
     return 5; 
    } 
}; 


// SFINAE test 
template <typename T> 
class has_operator_plusplus 
{ 
    typedef char one; 
    typedef long two; 

    template <typename C> static one test(decltype(&C::operator++)) ; 
    template <typename C> static two test(...); 

public: 
    enum { value = sizeof(test<T>(0)) == sizeof(char) }; 
}; 


int main(int argc, char *argv[]) 
{ 
    // the first check breaks the build 
    //static_assert(has_operator_plusplus<Hello>::value, "has no operator"); 
    static_assert(has_operator_plusplus<Generic>::value, "has no operator"); 
} 

這是一個好的設計?

是的,因爲破壞構建,捕獲錯誤時的速度非常快,而且類的用戶doesn't有閱讀的文檔(編程時,大多數人通常跳過這一部分)

+0

請問什麼是測試(...)的含義?我不太清楚這裏有三個點的語法。 – DawidPi

+0

@DawidPi請參閱[variadic函數](http://en.cppreference.com/w/cpp/utility/variadic) –

2

是的,你可以實現這樣的模板類。您可以使用SFINAE來測試各種成員的存在,如果它們不正確,static_assert。儘管我不確定爲什麼你想在C++ 11世界中定義typedef。

對代碼進行額外檢查總是一個好主意。