c++ - Template function that matches only certain types? -


i want define function template:

template<typename t> void foo(t arg) 

but want t match types. specifically, t should derive (maybe through multiple inheritance) form base class. otherwise template shouldn't included in overload set.

how can this?

use sfinae std::is_base_of:

template <typename t,           typename = std::enable_if_t<               std::is_base_of<foo, t>::value           >> void foo(t arg); 

that include foo in overload set if t inherits foo. note includes ambiguous , inaccessible bases well. if want solution allows ts inherit publicly , unambiguously foo, can instead use std::is_convertible:

template <typename t,           typename = std::enable_if_t<               std::is_convertible<t*, foo*>::value           >> void foo(t arg); 

note reversal of arguments.

regardless of form pick, can aliased brevity:

template <typename t> using enable_if_foo = std::enable_if_t<std::is_base_of<foo, t>::value>;  template <typename t,           typename = enable_if_foo<t>> void foo(t arg); 

this works because std::enable_if has nested type named type if , if boolean passed in true. if std::is_base_of<foo, t>::value true, enable_if_t gets instantiated void, if had written:

template <typename t,           typename = void> void foo(t arg); 

but, if t not inherit foo, type trait evaluate false, , std::enable_if_t<false> substitution failure - there no typename enable_if<false>::type. might expect compile error, substitution failure is not an error (sfinae). it's template deduction failure. effect foo<t> removed set of viable overload candidates in case, no different other template deduction failure.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -