2017-01-09 20 views
20

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

+17

爲什麼downvotes?當然,它是基本的,但問題是完整的,清晰的,OP甚至包含一個編譯器版本! – TartanLlama

+3

'「Helloworld」'不是'std :: string'。但''Helloworld's'會。 – Jarod42

+2

@TartanLlama:我想這是因爲用戶想要使用'typeid'編寫可怕的脆弱代碼。 –

回答

22

在這個調用

test_template("Helloworld"); // Does not print string 

參數"Helloworld"是一個字符串文字具有類型const char[11]

因爲函數的參數是一個被引用類型

void test_template(const T &t) 
          ^^^ 

然後函數的參數(更精確的參數)內具有類型const char (&t)[11]

C++中的字符串常量具有常量字符數組的類型,其元素個數等於字符串字符中的字符數加上終止零。

在這個調用

test_template(str); 

參數的類型爲std::string,因爲變量str聲明如下

string str = "ok"; 
^^^^^^ 

它是由字符串初始化文字"ok"但對象本身的類型是std::string的。

+1

'conat char'是'const char'? (我無法僅通過一次更改提交編輯。) –

+0

@ChristopheStrobbe你是什麼意思? –

+0

那麼,在你的答案中'conat' in'conat char(&t)[11]'。 –

9

"Helloworld"字符串文字字符的常數陣列。

std::string類有一個構造函數,它可以將指針指向字符串文本,但字符串文本本身不是std::string對象。


作爲一個側面說明,使用像你這樣的功能被認爲是代碼味道和糟糕的設計。使用重載的函數,而不是使用不同的參數這也將解決你的問題與字符串。

+3

同意,這裏沒有模板。沒有共同的功能。 – AndyG

+1

謝謝!我會考慮使用重載函數。 – Meehatpa

16

C++中的字符串文字的類型爲const char[N+1],其中N是字符串中的字符數。 std::string是一個標準的庫類,它擁有一個字符串並對其提供一些操作。 A std::string可以從const char[N]構建,但它們不是一回事。

相關問題