c++ - Templated functions overload return type -


the following doesn't partial specialization (that cannot happen on templated function). plus functions don't overload return type. what's going on in following code??

#include <iostream> #include <string> #include <vector>  template<typename t> t foo() {  std::cout << "first";  return t();    }   template<typename t, typename u> std::pair<t,u> foo() {  std::cout << "second";  return std::make_pair<t,u>(t(),u());  }  int main() {     foo<int>();     foo<int,char>(); } 

you have 2 overloads of foo (really 2 function templates named foo). 1 takes 1 template type argument:

template<typename t> t foo(); 

and 1 takes 2 template type arguments:

template<typename t, typename u> std::pair<t,u> foo(); 

you allowed overload on different template arguments. add overloads take non-type arguments:

template <int i> void foo() {     std::cout << "third"; } 

this separate, valid overload too. can't separately add:

template <typename u> u* foo(); 

because have 2 different function templates named foo take single template argument , there's no way compiler know 1 meant - have guaranteed ambiguous overload.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -