[英]C++ compile-time type checking
想知道是否有可能根據類型是否派生自特定類而分支的模板函數。 這大致就是我的想法:
class IEditable {};
class EditableThing : public IEditable {};
class NonEditableThing {};
template<typename T>
RegisterEditable( string name ) {
// If T derives from IEditable, add to a list; otherwise do nothing - possible?
}
int main() {
RegisterEditable<EditableThing>( "EditableThing" ); // should add to a list
RegisterEditable<NonEditableThing>( "NonEditableThing" ); // should do nothing
}
如果有人有任何想法讓我知道! :)
編輯:我應該添加,我不想實例化/構造給定的對象只是為了檢查其類型。
這是std::is_base_of
的實現:
#include <type_traits>
template <typename T>
void RegisterEditable( string name ) {
if ( std::is_base_of<IEditable, T>::value ) {
// add to the list
}
}
正如@Lightness所指出的,type_traits是答案。
C ++ 11包含了boost
type_trait的功能: http : //en.cppreference.com/w/cpp/types/is_base_of
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.