I referred to http://en.cppreference.com/w/cpp/language/typeid to write code which does different things for different types.
The code is as below and the explanation is given in the comments.
#include <iostream>
#include <typeinfo>
using namespace std;
template <typename T>
void test_template(const T &t)
{
if (typeid(t) == typeid(double))
cout <<"double\n";
if (typeid(t) == typeid(string))
cout <<"string\n";
if (typeid(t) == typeid(int))
cout <<"int\n";
}
int main()
{
auto a = -1;
string str = "ok";
test_template(a); // Prints int
test_template("Helloworld"); // Does not print string
test_template(str); // Prints string
test_template(10.00); // Prints double
return 0;
}
Why does test_template(str)
print "string" whereas test_template("Helloworld")
does not?
BTW, my g++ version is g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609.
In this call
the argument
"Helloworld"
is a string literal that has typeconst char[11]
.Because the function parameter is a referenced type
then within the function the argument (more precisely the parameter) has the type
const char ( &t )[11]
.String literals in C++ have types of constant character arrays with the number of elements equal to the number of characters in string literal plus the terminating zero.
In this call
the argument has type
std::string
because the variablestr
is declared likeIt was initialized by the string literal
"ok"
nevertheless the object itself is of the typestd::string
.