c++ - Default template argument when using std::enable_if as templ. param.: why OK with two template functions that differ only in the enable_if parameter? -


in language reference of std::enable_if @ cppreference following note included

notes

a common mistake declare 2 function templates that differ in default template arguments. illegal because default template arguments not part of function template's signature, , declaring 2 different function templates same signature illegal.

in template functions in example below, seems me situation occurs. i.e., 2 template functions onlyforderivedobjects(...) seem (to me) differ default template arguments. realize missing here, , can explain me, or point me in direction might find epiphany myself.

  • question: w.r.t. quote above, why example below compile , run fine: misclassify typename std::enable_if ... part in template functions below when consider yield situation 2 template functions differ in default template argument?

example

base , derived classes:

class basea { public:   int getint() const { return 21; }; };  class deriveda : public basea {};  class baseb { public:   int getanotherint() const { return 33; }; };  class derivedb : public baseb {}; 

with following template functions

/* template functions that, seemingly, differ in    default template arguments? */ template< class t,           typename std::enable_if<std::is_base_of<basea, t>::value>::type* = nullptr > int onlyforderivedobjects(const t& obj) {   return 2*obj.getint(); }  template< class t,           typename std::enable_if<std::is_base_of<baseb, t>::value>::type* = nullptr > int onlyforderivedobjects(const t& obj) {   return 3*obj.getanotherint(); } 

compiles , runs fine (g++ -wall -std=c++11 ..., g++ 4.9.3)

#include <iostream> #include <type_traits>  /* ... classes , template functions above */  /* template argument deduction seems work fine */ int main() {   deriveda* obja = new deriveda();   derivedb* objb = new derivedb();    std::cout << onlyforderivedobjects(*obja) << std::endl; // 42   std::cout << onlyforderivedobjects(*objb) << std::endl; // 99    return 0; } 

notes

a common mistake declare 2 function templates differ in default template arguments. illegal because default template arguments not part of function template's signature, , declaring 2 different function templates same signature illegal.

your functions don't differ in default template arguments, differ in template parameters, have different signatures.

in both cases default template argument nullptr, second template parameter different in each case.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -