簡體   English   中英

在 function 模板中獲取類型別名后面的類型名稱

[英]Get name of type behind type alias in function template

我正在使用 Visual Studio 2013。

當我需要知道編譯器為我的模板參數推導出什么類型時,我通常會觸發這樣的編譯器錯誤:

template <typename U>
struct TD;

template <typename T>
void f(T) {
    TD<T> t{};
}

int main() {
    f(1);
}

這是有效的,正如 Visual Studio 會告訴我的那樣,我試圖用一個int實例化我未定義的struct TD

error C2079: 't' uses undefined struct 'TD<T>'
        with
        [
            T=int
        ]
note: see reference to function template instantiation 'void f<int>(T)' being compiled
        with
        [
            T=int
        ]

但是,如果我想知道類型別名背后的類型是什么,上述技巧在 Visual Studio 上變得毫無用處。 例如以下內容:

template <typename T>
void f(T) {
    using unsigned_int_t = typename std::make_unsigned<T>::type;
    TD<unsigned_int_t> t{};
}

將產生:

error C2079: 't' uses undefined struct 'TD<unsigned_int_t>'
note: see reference to function template instantiation 'void f<int>(T)' being compiled
        with
        [
            T=int
        ]

而 GCC 會告訴我unsigned_int_t是一個unsigned int

error: 'TD<unsigned int> t' has incomplete type
   10 |     TD<unsigned_int_t> t{};

那么,有沒有辦法通過 Visual Studio 2013 獲取類型別名后面的類型名稱?

注意:我已經在編譯時查看了 Print template typename但沒有答案對我有用。

您可以使用typeid (typeid 運算符允許在運行時確定 object 的類型)。 試試下面的代碼片段:

#include <iostream> 
#include <string> 
#include <typeinfo> 
using namespace std;
template <typename U>
struct TD {};

//template <typename T>
//void f(T) {
//    TD<T> t{};
//}
template <typename T>
void f(T) {
    using unsigned_int_t = typename std::make_unsigned<T>::type;
    TD<unsigned_int_t> t{};
     cout<<typeid(t).name();

}

int main()
{
    f(1);
}

Output:

struct TD<unsigned int>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM