简体   繁体   English

在 function 模板中获取类型别名后面的类型名称

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

I'm working with Visual Studio 2013.我正在使用 Visual Studio 2013。

When I need to know what types the compiler deduced for my template parameters, I usually trigger a compiler error like this:当我需要知道编译器为我的模板参数推导出什么类型时,我通常会触发这样的编译器错误:

template <typename U>
struct TD;

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

int main() {
    f(1);
}

And this works, as Visual Studio will tell me I tried to instanciate my undefined struct TD with an int :这是有效的,正如 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
        ]

However, the above trick becomes useless on Visual Studio if I want to know what's the type behind a type alias.但是,如果我想知道类型别名背后的类型是什么,上述技巧在 Visual Studio 上变得毫无用处。 Eg the following:例如以下内容:

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

will produce:将产生:

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
        ]

Whereas GCC will tell me that unsigned_int_t is a unsigned int :而 GCC 会告诉我unsigned_int_t是一个unsigned int

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

So, is there a way to get the name of the type behind a type alias with Visual Studio 2013?那么,有没有办法通过 Visual Studio 2013 获取类型别名后面的类型名称?

Note: I already had a look at Print template typename at compile time but no answer worked for me.注意:我已经在编译时查看了 Print template typename但没有答案对我有用。

You can use typeid (The typeid operator allows the type of an object to be determined at run time).您可以使用typeid (typeid 运算符允许在运行时确定 object 的类型)。 Try the snippet below:试试下面的代码片段:

#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: Output:

struct TD<unsigned int>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM