Please note: This code may seem excessively complicated or raise further questions about how the Convert functions are going to do but I am intentionally only showing a very minimal example and the number of types and complexity of what I’m trying to do does warrant something of this nature. I also am aware that c++ does not support runtime reflection which might be the next obvious comment.
Essentially, I’m trying to implement a TypeConverter that has a number of member functions that allow it to return the result of converting from one type to another. The TypeConverter itself declares and implements the concrete functions required but the implementation of each function could use a different helper such as StructConverter. The helpers themselves need to access TypeConverter to help convert any complex types that they intern hold as members/children. The StructConverter itself is a template so that can be generic although some parts will need specific implementation.
However, I keep getting a linker error:
error: member access into incomplete type ‘TypeConverter’ a = tc.Convert(b,tc); ^
Originally I thought a forward class declaration would be all that was required but apparently not and I’ve been unable to figure out if what I’m trying to do is not possible (although to me it seems conceptually fine) or if I just haven’t found the appropriate c++ construct.
Many thanks in advance for any help in either getting this to build or suggestion of a pattern not too dissimilar approach that might help noting that using a template for StructConverter or similar is somewhat key to my design/desired outcome.
#include <string>
struct StructTypeA{
int time;
std::string source;
};
struct StructTypeB{
int time;
std::string source;
};
class TypeConverter;
template <typename A, typename B>
class StructConverter
{
public:
StructConverter(){;}
A Convert(B b, TypeConverter &tc)
{
A a;
a.source = b.source;
a.time = b.time;
// a.SomeMoreComplexType = tc.Convert(b.ComplexType);
a = tc.Convert(b, tc); // this would be recursive but illustrates the intent and produces linker error.
return a;
}
};
class TypeConverter
{
private:
StructConverter<StructTypeA, StructTypeB> sconverter;
public:
StructTypeA Convert(StructTypeB b, TypeConverter &tc)
{
return sconverter.Convert(b, tc);
}
};
int main()
{
TypeConverter tc;
StructTypeB b;
b.source = "somewhere";
b.time = 5;
StructTypeA a = tc.Convert(b, tc);
return 0;
}