I referred to http://en.cppreference.com/w/cpp/language/typeid to write a code which does different things for different types.
Code is as below and 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;
}
I am wondering why test_template(str)
prints "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
"Helloworld"
is not astd::string
. But"Helloworld"s
would be. – Jarod42 6 hours ago