Restrict C++ Template Parameter to Subclass

前端 未结 7 1633
醉话见心
醉话见心 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:30

    With a C++11 compliant compiler, you can do something like this:

    template class MyClass {
    
        MyClass() {
            // Compile-time sanity check
            static_assert(std::is_base_of::value, "Derived not derived from BaseClass");
    
            // Do other construction related stuff...
            ...
       }
    }
    

    I've tested this out using the gcc 4.8.1 compiler inside a CYGWIN environment - so it should work in *nix environments as well.

提交回复
热议问题