是否有可能實現這樣的模板類來執行設計合同?可能使用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有閱讀的文檔(編程時,大多數人通常跳過這一部分)
HTTP:也許吧?//www.boost.org/doc/libs/1_48_0/libs/type_traits/doc/html/boost_typetraits/category/value_traits/operators.html – BoBTFish
[漂亮的打印機](http://stackoverflow.com/q/4850473/596781)有一個C++ 11特徵類來檢查一個類型是否有迭代器類型,以及'begin' /'end'函數是否返回該迭代器類型。 –
@Kerrek謝謝你的例子。我節省了幾個人時間。 :) – Ram