How to Constrain a Template to Only Accept Specific Types in C
In Java, generic classes can be defined to accept only types that inherit from a specific class:
public class ObservableList<T extends List> { /* ... */ }
This is achieved using the extends keyword.
Equivalent in C
Unlike Java, C does not have a direct equivalent to the extends keyword for constraining templates. However, there is a way to achieve similar constraints using the std::is_base_of type trait in C 11:
#include <type_traits> template<typename T> class observable_list { static_assert(std::is_base_of<list, T>::value, "T must inherit from list"); // code here.. };
Alternative Approaches
While this approach works, it breaks away from typical C design principles. Instead, it may be more appropriate to use traits-based constraints:
#include <type_traits> template<typename T> class observable_list { static_assert(has_const_iterator<T>::value, "Must have a const_iterator typedef"); static_assert(has_begin_end<T>::value, "Must have begin and end member functions"); // code here... }; template<typename T> struct has_const_iterator : std::false_type {}; template<typename T> struct has_const_iterator<T, Void<typename T::const_iterator>> : std::true_type {}; struct has_begin_end_impl { template<typename T, typename Begin = decltype(std::declval<const T&>().begin()), typename End = decltype(std::declval<const T&>().end())> static std::true_type test(int); template<typename... Args> static std::false_type test(...); }; template<typename T> struct has_begin_end : decltype(has_begin_end_impl::test<T>(0)) {}; using Void = typename void_<>::type; template<typename... Args> struct void_ { using type = void; };
This approach defines custom traits to check for specific requirements (e.g., existence of const_iterator, begin, and end functions). It provides more flexibility and allows for custom error messages.
The above is the detailed content of How Can I Restrict Template Types in C to Specific Inheritance or Functionality?. For more information, please follow other related articles on the PHP Chinese website!