#include <iostream>
using namespace std;
template<typename T>
void test() {
cout << "1";
}
template<>
void test<std::string>() {
cout << "2";
}开发者_StackOverflow中文版
int main() {
test<std::string()>(); //expected output 2 but actual output 1
}
Why is the output 1 and not 2?
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"
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
).
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.
精彩评论