vendredi 15 avril 2022

Template instances with different return types

As per this document, which says that[emphasis mine]:

The return type of a function has no effect on function overloading, therefore the same function signature with different return type will not be overloaded. Example: if there are two functions: int sum() and float sum(), these two will generate a compile-time error as function overloading is not possible here.

It's amazing that this code snippet works!

#include <type_traits>
#include <iostream>

template <typename T>
T foo(){return T{};}

template<>
int foo(){std::cout << "int" << std::endl; return int{};}

template<>
double foo(){std::cout << "double" << std::endl; return double{};}

int main() {
    foo<int>();
    foo<double>();
    foo<bool>();
}

You see, the code snippet below does not compile indeed(If you have a question in it, please see the quotation at the beginning of the post):

#include <type_traits>
#include <iostream>

int foo(){std::cout << "int" << std::endl; return int{};}

double foo(){std::cout << "double" << std::endl; return double{};}

int main() {
}

Aucun commentaire:

Enregistrer un commentaire