1

I'm working with another persons code that uses a function doSomething that depends on two templates: stage and T. I know that they can just take the states (Micro, DerivedOne) or (Macro, DerivedTwo)

In doSomething I now need to cast DerivedTwo to BaseTwo and DerivedOne to BaseOne. As seen in the code the conversions are only made when the stage is right, i.e.they are always o.k. Still I get compile errors because it is not possible to cast DerivedOne to BaseTwo even though this cast is never made.

Question: How can I get this code to compile without changing the general structure of the involved classes and templates? (This would break to many other parts of the code). Preferably I only want to change doSomething.

The cast occurs b.c. I need to call an overloaded function that can either take BaseOne or BaseTwo. Hence, to pass DerivedTwo I need to explicitly cast it.

aTest.h

enum  Stage {
    Micro,
    Macro
};

class BaseOne
{
 int a;
};

class BaseTwo
{
int b;
};


class DerivedOne : public  BaseOne
{
 int c;
};

class DerivedTwo: public  BaseTwo, public  BaseOne
{
int d;
};

template  <Stage stage>
class Doer{
    template <class T>
    void doSomething( T t);

};

aTest.cpp

#include "aTest.h"

template< Stage stage >
template < class T >
void Doer<stage>::doSomething(T t) {


 //depending on stage we need to cast t to BaseOne or BaseTwo
 if( stage == Micro )
 {
  overloadedFunction( (BaseOne) t );
 }
 if( stage == Macro )
 {
  overloadedFunction( (BaseTwo) t );
 }



}


template  class Doer<Micro>;
template class Doer<Macro>;


template void Doer<Micro>::doSomething(DerivedOne t);
template void Doer<Macro>::doSomething(DerivedTwo t);
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Ricardo
  • 245
  • 1
  • 9
  • even though the cast is never made? According to this reasoning also `if (1==0) { syntax error; }` should compile. The code containing the cast is instantiated, so it has to be valid. I am not fluent on c++11 and beyond template stuff, but maybe a constexpr if may help – 463035818_is_not_an_ai Oct 19 '17 at 12:34
  • `if constexpr (..)` in C++17. – Jarod42 Oct 19 '17 at 12:35

1 Answers1

1

You could use:

if constexpr (stage == Macro)
     overloadedFunction( (BaseTwo) t );

Now why will this come in handy?

Because now that the if-statement contains constexpr, it will evaluate its condition at compile time, and will compile its body, only if the condition evaluates to true. That means that the body might be ill-formed, and yet the code to be able to compile. Read more here.

gsamaras
  • 71,951
  • 46
  • 188
  • 305