考虑如下代码:
#include <type_traits> #include <iostream> #include <vector> using namespace std; template <typename T, typename = void> struct RangeConcept : std::false_type {}; template <typename T> struct RangeConcept<T, std::void_t< decltype( std::declval<T >().begin() ), decltype( std::declval<T >().end() ) > > : std::true_type {}; template<typename Cont> void show( Cont c){ static_assert( RangeConcept< Cont >::value, "must be a range. means.. it has begin() and end()" ); }
int main() { std::vector<int> vec{1,2,3,4,5}; show(vec); }
这就是C++17带来的void_t神器。写个静态断言无比容易。手写个Concept检查也不再是C++库开发者的专利了。
参考:http://en.cppreference.com/w/cpp/types/void_t