看完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/