Hacker News new | past | comments | ask | show | jobs | submit login

> I'm curious: what's wrong with myFunc(List<BaseClass * >) ??

Well, nothing I suppose, except BaseClass cannot then be a template, and you cannot have derived class-specific return types like a template would allow.

So, having BaseClassInt type return int from some function but BaseClassLong return a long gets more challenging than it should be. (I recognize all my examples so far had a void return type, that was just for simplicity).

> But both BaseClass * and DerivedClass * are compatible with each other, and may convert into each other, as long as you know the pointer goes to the right kind of class)

Which loses type safety, unfortunately.

> In this case, we've created a static_assert (aka: a compile-time error will pop up) if T does not convert into BaseClass

I'll look into the static_assert() option, could prove useful in some cases.

At the end of the day, there are two things at play here - my lack of C++ familiarity, and in some cases it's just how C++ is.

It is a strange feeling though, having a language limit your expressiveness for the first time...




> Well, nothing I suppose, except BaseClass cannot then be a template

    template <class T>
    void myFunc(List<T*>){
        static_assert(stuff about T that you want to guarantee at compile time); 
    }
See here: https://en.cppreference.com/w/cpp/header/type_traits

For a list of common functions used for compile-time type checking.


Thank you for this conversation. You've given me some homework to read up on, and I appreciate it a lot!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: