小编Mee*_*tpa的帖子

在参数中输入变量与字符串的std :: string的id?

我提到http://en.cppreference.com/w/cpp/language/typeid来编写代码,它为不同的类型做了不同的事情.

代码如下,注释中给出了解释.

#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;
}
Run Code Online (Sandbox Code Playgroud)

为什么test_template(str)打印"字符串"而test_template("Helloworld")不是?

顺便说一句,我的g ++版本是g ++(Ubuntu 5.4.0-6ubuntu1~16.04.4)5.4.0 20160609.

c++ string string-literals c++11

19
推荐指数
3
解决办法
2093
查看次数

标签 统计

c++ ×1

c++11 ×1

string ×1

string-literals ×1