Reputation: 55
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);
}
Upvotes: 0
Views: 207
Reputation: 9825
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.
Upvotes: 2