Restrict C++ Template Parameter to Subclass

前端 未结 7 1625
醉话见心
醉话见心 2020-11-28 22:04

How can I force a template parameter T to be a subclass of a specific class Baseclass? Something like this:

template 

        
7条回答
  •  野性不改
    2020-11-28 22:44

    Since C++11 you do not need Boost or static_assert. C++11 introduces is_base_of and enable_if. C++14 introduces the convenience type enable_if_t, but if you are stuck with C++11, you can simply use enable_if::type instead.

    Alternative 1

    David Rodríguez's solution may be rewritten as follows:

    #include 
    
    using namespace std;
    
    template 
    enable_if_t::value, void> function() {
       // This function will only be considered by the compiler if
       // T actualy derived from Base
    }
    

    Alternative 2

    Since C++17, we have is_base_of_v. The solution can be further rewritten to:

    #include 
    
    using namespace std;
    
    template 
    enable_if_t, void> function() {
       // This function will only be considered by the compiler if
       // T actualy derived from Base
    }
    

    Alternative 3

    You could also just restrict the the whole template. You could use this method for defining whole classes. Note how the second parameter of enable_if_t has been removed (it was previously set to void). Its default value is actually void, but it doesn't matter, as we are not using it.

    #include 
    
    using namespace std;
    
    template >>
    void function() {
       // This function will only be considered by the compiler if
       // T actualy derived from Base
    }
    

    From the documentation of template parameters, we see that typename = enable_if_t... is a template parameter with an empty name. We are simply using it to ensure that a type's definition exists. In particular, enable_if_t will not be defined if Base is not a base of T.

    The technique above is given as an example in enable_if.

提交回复
热议问题