C <T> derived from T, is it safe?

I have a problem that can be solved well if I can specify a base class ( C derived from T

) for a specific class C<T>

.

I've never done this before, so I create a short test case and it works .

#include <iostream>
using namespace std;

class B{
    public: int k=5;
};
template<class T> class C : public T{};

int main() {
    C<B> c;
    std::cout<<c.k<<std::endl;
    return 0;
}

      

Question

Is this on the edge of C ++ syntax? / Is this definition defined?
Is it safe to use it in real business? Is there something I should be specific about? (I hope they are not.)
What is this technique called (if any)?

+3


source to share


1 answer


It's not "on the edge of C ++", but perfectly legal as long as T

is a type to get from. I don't know of any specific name for this "template".



Note that you can either get from std::remove_reference_t<T>

instead (for doing things like C<B&>

valid) or leave it T

to compile for C<B&>

and vice versa - it depends.

+3


source







All Articles