c++ - Template function overload for base class -



c++ - Template function overload for base class -

how forcefulness compiler pick template function overload base of operations class?

here illustration illustrates question

#include <iostream> class {}; class b : public {}; template <class t> void f (const t& t) { std::cout << "generic f" << std::endl; } void f (const a& a) { std::cout << "overload a" << std::endl; } template <class t> void call_f (const t& t) { f (t); } int main() { call_f (10); call_f (a()); call_f (b()); homecoming 0; }

it produces output

generic f overload generic f

why doesn't compiler pick f (const a&) in 3rd case? upd: ok, 1 clear void f<b> (const b&) improve void f (const a&), i'm still looking reply 2nd question.

and possible forcefulness without casting b a?

using call_f(b()) results in phone call `f() best matched template version. non-template version conversion required. result, template chosen. if template , non-template as options, non-template preferred.

if want non-template called, you'll need create template non-option. example, template implemented like

#include <type_traits> template <class t> typename std::enable_if<!std::is_base_of<a, t>::value>::type f(t const&) { std::cout << "generic f\n"; }

if c++11 can't used either implement version of std::is_base_of<...>, utilize version boost or utilize simple dispatch:

struct true_type {}; struct false_type {}; true_type a_is_base_of(a const*) { homecoming true_type(); } false_type a_is_base_of(void const*) { homecoming false_type(); } template <class t> void f (t const&, false_type) { std::cout << "generic f\n"; } void f (a const&, true_type) { std::cout << "overload a\n"; } template <class t> void call_f (const t& t) { f (t, a_is_base_of(&t)); }

c++ function templates overloading

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -