mardi 1 février 2022

Call different initializer after type checking

I have a generic class, where two of the generics are going to be identical 90% of the time, but on the off chance that they are separate types, I need to perform member initialization a little bit differently.

template<typename S, typename T = S>
class MyClass {
    MyClass(const Options<S> & opts) {
        if (std::is_same<S,T>::value) {
            thing.reset(new T(opts.get_s_thing()));   // 90% of time, use type S in args to initialize thing
        } else {
            thing.reset(new T());              // Special case, types differ, so create a new one
        }
        //
        // Other constructor things...
        //
    }

    std::shared_ptr<T> thing;
};

Only thing is, since type-checking is done at compile time, the thing.reset(opts.get_s_thing()); line throws an error if I create MyClass with an explicitly different type for T. But because the types differ, that line would never get called anyways. Is there some preprocessor directive I can use here? What strategy should I take?

Changing the constructor signature in MyClass is not an option, since this is part of a VERY large codebase. T is a new thing, so I have more freedom in deciding the "standard interface" for Ts.

Aucun commentaire:

Enregistrer un commentaire