samedi 1 juillet 2017

c++ conditional generic class object

I have the following piece of code:

helper.hpp

struct A{
uint32_t a, b;
};

struct B{
uint32_t a, b;
};

template <typename T>
struct C{
T barcode;
};

Now based on some condition I want to create appropriate struct object in the main.cpp

if(//something){
  C<A> obj;
}
else{
  C<B> obj;
}

Now the problem is since it's inside the if scope I can't access outside it. One way to handle it would be to return the object from a function, something like this:

template <typename T> 
C<T> getObject(){
  if(//something){
    return C<A>;
  }
  else{
    return C<B>;
  }
}

auto obj = getObject()

but this is giving me following compilation error:

error: no matching function for call to 'getObject() note: couldn't deduce template parameter 'T'

Really appreciate any help.

Aucun commentaire:

Enregistrer un commentaire