[英]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.