C/C++ Arena

Step 4 of 6

Writing your own trait

A trait is just a template struct with a value, where specializations give the answers. The standard ones are written exactly like this:

template <typename T>
struct is_vector : std::false_type {};          // default: no

template <typename T, typename A>
struct is_vector<std::vector<T, A>> : std::true_type {};   // any vector: yes

template <typename T>
inline constexpr bool is_vector_v = is_vector<T>::value;

The second one is a partial specialization: it's still a template (over T and the allocator A), but only matches vectors.

Your turn: write the is_vector trait and is_vector_v, then use it in size_of(const T& x): for a vector, return its size(); for anything else, return 1.

Previous: Type traits Next: Constraining templates with concepts