vij
vij

Reputation: 95

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?

Upvotes: 5

Views: 140

Answers (3)

Prasoon Saurav
Prasoon Saurav

Reputation: 92864

std::string() is a typeid. A typeid is a simple declaration with missing declarator id.

In a template-argument, if there is an ambiguity between a type-id and an expression the call is resolved to a type-id. So your code outputs 1

You need to remove the parentheses () in order to get 2 as the output i.e foo<std::string>() would give you output 2.

Upvotes: 0

&#201;ric Malenfant
&#201;ric Malenfant

Reputation: 14148

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"

Upvotes: 9

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

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).

Upvotes: 2

Related Questions