如何从typedef中获取模板类型

How to get the template type from a typedef

本文关键字:类型 获取 typedef      更新时间:2023-10-16

我的目标是自动替换使用INT16而不将INT16作为模板参数:

#include <windows.h>
typedef Address<INT16> Address2Bytes;
// Address is a class made by me with constructor Address<Data>(const char*, const Data&)
template <typename Addr>
void doStuff(const char* addressName, const ????& addressData)
{
Addr address(addressName, addressData);// This variable MUST be created here
// Do stuff
}
void main(void)
{
doStuff<Address2Bytes>("name", 0x0);// Can't pass INT16 as a template (please don't ask why)
}

解释为什么我不能用INT16替换:真正的doStuff函数是这样的:

template <typename Addr>
void freeze(const String& processName, const String& addressName, const ????& data)
{
Process process = processes[processName];
Addr& address = process.getAddress<Addr>(addressName);
address.data = data;
address.frozen = true;
}

这是一个库函数,库用户不需要知道INT16是什么,他只需要知道指向2字节内存的地址。

首先,您可以推断addressData的类型,如果类型无效,则函数无法在构造函数中编译:

template <typename Addr, typename DataType>
void doStuff(const char*, const DataType& );

如果由于某种原因这不令人满意,您可以使用类型特征来确定Address上的模板类型是什么:

template <typename T> struct address_type;
template <typename T>
struct address_type<Address<T> > {
typedef T type;
};

然后你可以在你的功能中使用:

template <typename Addr>
void doStuff(const char* addressName,
const typename address_type<Addr>::type& addressData)
{ .. }

当您调用doStuff<Address2Bytes>时,它将实例化address_type<Address2Bytes>模板,其type成员将是INT16。如果您试图用一个不是Address的类型调用doStuff,这将无法编译,这可能是可以的