Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a specialized template function, when there is also a non-template function in C++

Tags:

In this example, how is it possible to call the second function?

template<class T>
T square(T a) {
    std::cout << "using generic version to square " << a << std::endl;
    return a*a;
}

/// "int" is so special -- provide a specialized function template
template<>
int square(int a) {
    std::cout << "using specialized generic version to square " << a << std::endl;
    return a*a;
}

/// and there's one more: a non-template square function for int
int square(int a) {
    std::cout << "using explicit version to square " << a << std::endl;
    return a*a;
}

Thanks in advance!

like image 766
user2343039 Avatar asked Mar 23 '16 11:03

user2343039


1 Answers

Call the specialization by explicitly specifying the template argument:

square<int>(2);

Live Demo

like image 76
101010 Avatar answered Nov 15 '22 07:11

101010