2010-12-23 89 views
1

以下代碼在調用模板化函數時打印出字符串「T」而不是實際的類型名稱。有沒有辦法獲得真正的類型名稱,而無需向模板類型添加任何內容?如何將模板化的類型名稱作爲字符串?

#define stringify(a) #a 
#define tostring(a) stringify(a) 

template <typename T> 
void function_foo(T a, T b) 
{ 
    cout << tostring(T) << endl; 
    ... 
} 
+1

重複數據刪除:在這裏看到http://stackoverflow.com/questions/1488186/stringifying-template-arguments – Abhay 2010-12-23 14:34:05

+0

或http://stackoverflow.com/questions/4484982/how-to-convert-typename-t -to-string-in-c – 2010-12-23 14:35:21

回答

3

模板不能像那樣工作。在您的模板T指定一個類型,而不是令牌序列:

typedef int lolztype; 
typedef int lulztype; 

function_foo<lolztype>(0, 0); 
function_foo<lulztype>(0, 0); // calls the *same* template 

沒有辦法分別獲得lolztypelulztype。你可以嘗試的是使用typeid(T).name(),但這不是非常有用,因爲它不需要人類可讀,甚至不需要爲每種類型區分。

你可以嘗試使用geordi's文件type_strings.hpp,它可以在用GCC編譯時打印出一個可讀的字符串。

1

使用:

#include <typeinfo> 

template <typename T> 
void function_foo(T a, T b) 
{ 
    cout << typeid(a).name() << endl; 
    ... 
} 

什麼typeid的()名稱()返回的是依賴。平臺,但是是一個字符串可能代表你的類型。

+0

實際上這在技術上是不正確的。從[手冊](http://www.cplusplus.com/reference/typeinfo/type_info/name/): 「返回可以標識類型的空終止字符序列。」。 所以它可能會或可能不會實際「代表您的類型」。 – 2017-05-25 04:20:25

1

typeid運營商。但請注意,name()字符串是實現定義的。特別是,它通常涉及到一些名稱混亂。一些實現還提供了另一種公共方法來獲得「漂亮」字符串;檢查您的<typeinfo>標題。

#include <typeinfo> 
template <typename T> 
void function_foo(T a, T b) 
{ 
    std::cout << typeid(a).name() << std::endl; 
    // ... 
} 
0

你唯一的選擇是自己定義這個反射,也許通過一個接口返回它的具體類型的字符串表示。

struct my_type : public reflects { 
    my_type(); 
    static const std::string& type_name = "my_type"; 
}; 
相關問題