Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template call: Actual specialization not called

#include <iostream>

using namespace std;

template<typename T>
void test() {
   cout << "1";
}

template<>
void test<std::string>() {
   cout << "2";
}

int main() {
   test<std::string()>(); //expected output 2 but actual output 1
}

Why is the output 1 and not 2?

like image 706
vij Avatar asked May 20 '11 17:05

vij


2 Answers

test<std::string> (note: no parentheses at the end) would yield what you expect.

Writing it as test<std::string()> instantiates the template with the type "function taking no arguments and returning std::string"

like image 157
Éric Malenfant Avatar answered Nov 14 '22 03:11

Éric Malenfant


Did you mean to invoke the function like: test<std::string>()?

In your test<std::string()>(), the template parameter is not std::string but a function type (a function taking no arguments and returning std::string).

like image 2
Lightness Races in Orbit Avatar answered Nov 14 '22 01:11

Lightness Races in Orbit