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

Mee*_*tpa 19 c++ string string-literals c++11

我提到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.

Vla*_*cow 21

在这个电话中

test_template("Helloworld"); // Does not print string
Run Code Online (Sandbox Code Playgroud)

参数"Helloworld"是一个具有类型的字符串文字const char[11].

因为函数参数是引用类型

void test_template(const T &t) 
                          ^^^
Run Code Online (Sandbox Code Playgroud)

然后在函数内,参数(更确切地说是参数)具有类型const char ( &t )[11].

C++中的字符串文字具有常量字符数组的类型,其元素数等于字符串文字中的字符数加上终止零.

在这个电话中

test_template(str); 
Run Code Online (Sandbox Code Playgroud)

参数有类型,std::string因为变量str声明为

string str = "ok";
^^^^^^
Run Code Online (Sandbox Code Playgroud)

它由字符串文字初始化,"ok"但对象本身属于该类型std::string.


Tar*_*ama 16

C++中的字符串文字是类型const char[N+1],其中N是字符串中的字符数.std::string是一个标准库类,它拥有一个字符串并在其上提供许多操作.A std::string可以用a构造const char[N],但它们不是同一个东西.


Som*_*ude 9

字符串文字就像"Helloworld"是常量字符数组.

std::string班有一个构造函数,可以采取指向字符串常量,而是一个字符串文字本身不是一个std::string对象.


作为旁注,使用像你这样的函数被认为是代码嗅觉和糟糕的设计.使用重载函数代替不同的参数.这也将解决你的字符串问题.

  • 同意,这里有一个模板是没有意义的.没有共同的功能. (3认同)