0

Consider these lines of code. When I try to compile the compiler will show errors like 'a' is not a member of 'DataType1'. I understand how the compiler treats these as errors but is there any way I could avoid this or another method that works?

struct DataType1 { public: int x; };
struct DataType2 { public: int a; };

template <class E>
bool job2(E* newData, const int i){
  int something = 2;  
  if (i == 1) newData->x = something;
  if (i == 2) newData->a = something;
}

template <class E>
bool job1(List<E>* dataBase){
  E* newData = new E;
  job2(newData, 1);
  dataBase->push_back(newData);
}

template <class E>
int main(){
  List<DataType1>* dataBase = new List<DataType>;
  job1(dataBase);
}
7
  • You can turn the const int i variable into a template argument and specialize the templated function. But that brings a question: why don't you remove the i argument and just specialize on E? Commented Sep 23, 2019 at 9:13
  • 1
    Another way could be to define a set function with the same name (SetI()) in each DataType struct and call that instead newData->SetI(something). Commented Sep 23, 2019 at 9:16
  • 1
    If you can use C++17, and if you can pass i as template parameter, you can use if constexpr Commented Sep 23, 2019 at 9:16
  • @freakish I tried overloading with job2(DataType1* newData) but it couldn't compile with error cannot convert argument from E* to DataType1 Commented Sep 23, 2019 at 9:30
  • @HàHuyLongHải that's because you try to push_back an element of type E* to List<DataType1>. That's obviously wrong, even when E=DataType1. The problem is job1 function, not job2 specialization/overload. Not to mention that job1 leaks memory. Commented Sep 23, 2019 at 9:46

1 Answer 1

2

If you have C++17 at hand you can write:

template <class E>
bool job2(E* newData){
  int something = 2;  
  if constexpr (std::is_same_v<E, DataType1>) 
     newData->x = something;
  else 
     newData->a = something;
}

and discard i alltogether (if you only used it to distinguish between types).

Othwerwise, what argues against simply overloading your function?

bool job2(DataType1* newData){
  commonOperation();
  newData->x = something;
}

bool job2(DataType2* newData){
  commonOperation();
  newData->a = something;
}

where commonOperation is everything the functions have in common.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried the second one but it couldn't compile with error cannot convert argument from E* to DataType1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.