c++ - How to restrict typenames in template -
have function can accept 4 different types. , implementations similar.
template< typename t > void foo( std::string &&name, t value ){ //... }
typename t
must 1 of 4 predefined types. other typenames not acceptable, , should restricted @ compile-time.
possible write in c++?
<type_traits>
let generalize logic class template. how works take template parameter t
, parameter pack of ts
, start checking if t
same head
of list of types. if match found, inherit std::true_type
, done. if no match found, pop head , recursively instantiate same template tail of ts
. eventually, if no match found @ all, parameter pack size drop 0 , compiler instantiate base template class inherit std::false_type
. please check video better , in dept explanation mr. walter e. brown.
template<class t, class...> struct is_any_of: std::false_type{}; template<class t, class head, class... tail> struct is_any_of<t, head, tail...>: std::conditional_t< std::is_same<t, head>::value, std::true_type, is_any_of<t, tail...>> {};
now can sfinae over, using enable_if in english wording.
#include <type_traits> #include <string> template< class t, class = std::enable_if_t<is_any_of<t, int, float, unsigned, double>::value> > void foo(std::string &&str, t value) {} int main() { foo(std::string{"hello"}, 3); foo(std::string{"world"}, '0'); //compile-time error }
sfanie language feature, tool, that's used or abused achieve ask for,
the standard library component std::enable_if allows creating substitution failure in order enable or disable particular overloads based on condition evaluated @ compile time. fyi http://en.cppreference.com/w/cpp/language/sfinae.
note std::conditional_t<>
, std::enable_if_t<>
shorthanded std::conditional<>::type
, std::enable_if<>::type
respectively. simple replace these in code, should put typename
keyword before enable_if
then.
Comments
Post a Comment