vigs1990 vigs1990 - 16 days ago 5
C++ Question

auto with ternary operator and templates

I have a template class

template <typename T>
class foo;


There are 2 valid values for T, corresponding to:

using fooT1 = class foo<T1>;
using fooT2 = class foo<T2>;


I wanted to write code which looks like:

const auto* fooPtr = useFooT1 ? getFooT1Ptr() : getFooT2Ptr();


because the code using
fooPtr
in this function doesn't depend on whether fooPtr is of type
fooT1
or
fooT2


However, I get the following compiler error:

error: conditional expression between distinct pointer types ...


I understand that as per the C++ standard, there should be a common type that both can be casted to, so this approach may not work.

What's a good way to achieve this functionality without replicating a lot of code?

Answer

Indeed, C++ is statically typed, so the type of a variable can't depend on a runtime condition.

Instead, put the generic code into a template:

template <typename T> doStuff(foo<T> * f) {
    // stuff that works with any `foo` type
}

and call a different specialisation depending on the run-time variable

if (useFooT1) {
    doStuff(getFooT1Ptr());
} else {
    doStuff(getFooT2Ptr());
}
Comments