template specialization function c++

53 views Asked by At

This is my code:

#include <iostream>
using namespace std;

template< typename T >
T silnia( T w ) {
    cout << "not special" << endl;
}
template<>
int silnia<int>( int x ) {
    cout << "special" << endl;
}

int main() {

cout << silnia<double>(5) << endl;
cout << silnia<int>(5) << endl;

return 0;
}

And this is the output:

not special
nan
special
4712544

Can someone help me understand where there two additional lines came from ?

2

There are 2 answers

0
Cory Kramer On BEST ANSWER

You are likely getting a compiler warning (at least) telling you that your template returns a T and int respectively, yet you provide no return values, which is undefined behavior. You should return the type that the function claims it is going to.

template< typename T >
T silnia( T w ) {
    cout << "not special" << endl;
    return w;
}

template<>
int silnia<int>( int x ) {
    cout << "special" << endl;
    return x
}

Why does it matter? Because you are using std::cout to try to output the returned values of these function calls.

cout << silnia<double>(5) << endl;
cout << silnia<int>(5) << endl;
0
juanchopanza On

Both function templates have a return type, but the implementations don't return anything. You have undefined behaviour because you're attempting to use the return values. This has nothing to do with templates.

Here's a fixed version of your code:

#include <iostream>
using std::cout;
using std::endl;

template< typename T >
T silnia( T w ) {
    cout << "not special" << endl;
    return w;
}
template<>
int silnia<int>( int x ) {
    cout << "special" << endl;
    return x;
}

int main() {
  cout << silnia<double>(5) << endl;
  cout << silnia<int>(5) << endl;
}

Output

not special
5
special
5