我提到http://en.cppreference.com/w/cpp/language/typeid來編寫代碼,它們針對不同類型做了不同的事情。爲變量輸入std :: string的id類型和參數中的字符串?
代碼如下,說明在評論中給出。
#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;
}
爲什麼test_template(str)
打印 「弦」,而test_template("Helloworld")
不?
順便說一句,我的克++版本爲g ++(Ubuntu的5.4.0-6ubuntu1〜16.04.4)5.4.0 20160609.
爲什麼downvotes?當然,它是基本的,但問題是完整的,清晰的,OP甚至包含一個編譯器版本! – TartanLlama
'「Helloworld」'不是'std :: string'。但''Helloworld's'會。 – Jarod42
@TartanLlama:我想這是因爲用戶想要使用'typeid'編寫可怕的脆弱代碼。 –