c++templates

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.


Solution

  • 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
        }
    }