获取模板类型作为字符串

Edi*_*enz 2 c++ boost metaprogramming

在阅读了使用Boost.MPL的C++编译时字符串哈希,并考虑到我遇到的问题之后,我想到了以下内容.

我有基类:

template<class Command>
class Base {
  typedef Command CommandType;
}
Run Code Online (Sandbox Code Playgroud)

它应该是Commands类的实用程序基类,因此它们不需要自己定义和声明某些成员,它们只是从它们引用的类型继承Base.所以他们可以像这样使用:

class CommandInstantiatorA : public Base<CommandA>
{
public:
   static std::string GetID() { return "CommandInstantiatorA "; }
}
Run Code Online (Sandbox Code Playgroud)

但是,还有另一种方法(GetID)我无法"模板化",它通过应用程序返回一个唯一的ID.我希望能够散列传递给类Base的类型,因此其他类只需要指定类型.像这样的东西:

template <class Base>
class Base {
   typedef boost::hash_value(TO_STRING(Base)) ID; //should also be read as: typedef boost::hash_value("CommandA") ID;
   ...
}
Run Code Online (Sandbox Code Playgroud)

是否有这样的宏(TO_STRING)会在最后一个示例中产生结果"CommandA".Boost.MPL中有什么可以做到的吗?

RnR*_*RnR 7

不是在提升,但它只是C++的一部分所以我希望它会这样做 - 也许你可以考虑使用RTTI - 例如像http://en.wikipedia.org/wiki/Typeid

int main () {
Person person;
Employee employee;
Person *ptr = &employee;
// The string returned by typeid::name is implementation-defined
std::cout << typeid(person).name() << std::endl;   // Person (statically known at compile-time)
std::cout << typeid(employee).name() << std::endl; // Employee (statically known at compile-time)
std::cout << typeid(ptr).name() << std::endl;      // Person * (statically known at compile-time)
std::cout << typeid(*ptr).name() << std::endl;     // Employee (looked up dynamically at run-time
                                                   //           because it is the dereference of a
                                                  //           pointer to a  polymorphic class)
}
Run Code Online (Sandbox Code Playgroud)

  • 我要指出的是,RTTI仅在具有至少1个虚函数的类上可用.不难设计,但是当它不起作用并且你不知道为什么时会感到沮丧.请参阅:http://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI和http://www.cplusplus.com/reference/std/typeinfo/type_info/ (3认同)
  • 另一点,typeid可以直接应用于类型.它不一定是一个实例.例如,在您的示例中,typeid(Base).name()可以替换TO_STRING (2认同)