c++ - 将模板化类型作为字符串获取

标签 c++ boost metaprogramming

看完C++ compile-time string hashing with Boost.MPL ,考虑到我遇到的一个问题,我想到了以下内容。

我有基类:

template<class Command>
class Base {
  typedef Command CommandType;
}

它应该是 Commands 类的实用基类,因此它们不需要 typedef 和自己声明一些成员,它们只需从 Base 继承它们所引用的类型。所以它们可以这样使用:

class CommandInstantiatorA : public Base<CommandA>
{
public:
   static std::string GetID() { return "CommandInstantiatorA "; }
}

但是,还有一种我无法“模板化”的方法 (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;
   ...
}

在上一个示例中是否有这样一个宏 (TO_STRING) 会产生结果“CommandA”。 Boost.MPL 中有什么东西可以做到这一点吗?

最佳答案

不在 boost 中,但它只是 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)
}

关于c++ - 将模板化类型作为字符串获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1846911/

相关文章:

c++ - Array Class 数组的打印输出

c++ - boost::filesystem::path::lexically_normal: 这是不正确的行为吗?

ruby - 查找名称与字符串匹配的所有类

c++ - 为什么数字类型只有一个 `to_string()`?

java - 从 C++ 创建一个 android.graphics.Bitmap

c++ - 在应用程序重新启动 C++ Visual Studio 时保存编辑控件用户输入和恢复的有效方法

c++ - 在对象声明上下文中获取此类型

c++ - Boost property tree xml解析No such node()

c++ - 具有相同简单改编结构属性的 boost::spirit::qi 规则会产生编译错误

c++ - 对参数包中的每个元素应用函数