Rec*_*als 2 c++ macros templates class c-preprocessor
我有一个模板化的类,它根据作为类型参数传递的对象类型设置(命名)共享内存池.我想知道是否可能通过预处理器运算符或其他方式,有一种方法来"字符串化"类型名称,并附加一个标识符?
语法的一些东西:<classtype> _identifier
在哪里MyClass<int>生成int_identifier...
例如:
template<typename T>
class MyClass
{
private:
#define TYPENAME_STRING(s) T_#s
std::string m_typeName;
public:
MyClass(std::string objName = "ObjectName")
{
// This:
m_typeName = TYPENAME_STRING(objName.c_str());
// ...Obviously doesn't work, since this is the equivalent of typing:
m_typeName = "T_ObjectName";
// ...When what we really want is something like:
m_typeName = "int_ObjectName";
}
~MyClass();
};
Run Code Online (Sandbox Code Playgroud)
实现此功能对于完全根据作为类型参数传递的对象类型来命名,创建和管理伪独特内存池非常有用.
此外,是否有可能解决这一类型名,它前面加上一个标识符WITHOUT被"stringized"(即创建一个typedef 命名的 intObjectName)?
不,这是不可能的,至少不是那个级别.在编译之前评估宏,即T在评估示例中的模板类型参数之前评估宏.你可以做的是这样的事情:
#include <string>
#include <memory>
template <class T> struct TInfo;
template <class T> class MyClass;
#define TINFO(type) \
template <> struct TInfo<type> { \
static char const* getName() { \
return #type; \
} \
}; \
typedef MyClass<type> type##_Class; \
typedef std::unique_ptr<MyClass<type>> type##_UPtr;
template <class T>
class MyClass {
private:
std::string m_typeName;
public:
MyClass(std::string objName = "ObjectName")
: m_typeName(std::string(TInfo<T>::getName()) + "_" + objName)
{}
std::string const& getName() {
return m_typeName;
}
};
//usage:
#include <iostream>
TINFO(int);
int main()
{
int_UPtr pi(new int_Class());
std::cout << pi->getName() << '\n';
}
Run Code Online (Sandbox Code Playgroud)