2009-12-04 47 views
2

閱讀C++ compile-time string hashing with Boost.MPL後,考慮到我遇到的問題,我想到了以下內容。獲取作爲字符串的模板類型

我有基類:

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

它應該是爲命令類的實用程序的基類,所以他們並不需要的typedef,並宣佈自己的一些成員,他們僅僅是從Base引用它們引用的類型。所以它們可用於這樣的:

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

然而,存在這種其它方法(的getId),我不可能「模板化」,它返回throught應用程序的唯一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中有什麼可以做到的嗎?

回答

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) 
} 
+3

我要指出的是RTTI僅適用於帶班至少1個虛擬功能。不難設計,但當它不起作用時會感到沮喪,並且你不知道爲什麼。請參閱:http://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI和http://www.cplusplus.com/reference/std/typeinfo/type_info/ – KitsuneYMG 2009-12-04 13:34:40

+2

另一點,typeid可以直接應用於一種。它不一定是一個實例。例如例如,typeid(Base).name()可以代替TO_STRING – KitsuneYMG 2009-12-04 13:41:44

0

預處理(即宏)有一個字符串化操作可以用雙引號將任何標記包裹起來。這不能做你想做的事情,至少和寫法一樣,因爲它會將文字標記「Base」串起來,而不是替代模板參數。

1

您可以使用預處理字串 - 這可能並不能解決所有問題,但你能得到的字符串:

#include <iostream> 
using namespace std; 

#define ToString(x) #x 
struct C { static const string id; }; 

const string C::id = ToString(C_ID); 

int main() 
{ 
    C c; 
    cout << c.id << endl; 
} 

打印:

C_ID