Doubt about calling a template: actual specialization is 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 conclusion 1, not 2?

+5
source share
3 answers

test<std::string> (note: no brackets at the end) will give what you expect.

Writing it as test<std::string()>creates an instance of the template with a type function that takes no arguments and returns std :: string "

+9
source

Did you mean a function call like test<std::string>():?

In your test<std::string()>()template parameter is not std::string, but the type of function (the function takes no arguments and returns std::string).

+2
source

std::string() - typeid. - .

In the template argument, if there is ambiguity between the type identifier and the expression, the call is allowed to the type identifier. So your code outputs 1

You need to remove the parentheses ()to get 2 as the result ie foo<std::string>()will give you an output of 2.

0
source

All Articles