vigs1990 vigs1990 - 9 months ago 46
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
in this function doesn't depend on whether fooPtr is of type

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 Source

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) {
} else {