QuadrupleA
QuadrupleA

Reputation: 906

C++ compile-time branching (like a type switch) in templated function definition

Was wondering if it's possible to have a template function that can branch depending on whether the type is derived from a particular class. Here's roughly what I'm thinking:

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
}

If anyone has any ideas let me know! :)

Edit: I should add, I don't want to instantiate / construct the given object just to check its type.

Upvotes: 4

Views: 2323

Answers (2)

David G
David G

Reputation: 96790

Here is an implementation with 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
    }
}

Upvotes: 4

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275200

As @Lightness noted, type_traits are the answer.

C++11 has included that boost type_trait: http://en.cppreference.com/w/cpp/types/is_base_of

Upvotes: 2

Related Questions