I am writing a template function like that:
template<typename T>
std::string EncodeData(int DataType, T Data, std::string ReadCommandID, std::string& ThisID);
The type T
that I want to use is some different structs, for example:
struct A
{
int A_data;
bool A_data_2;
// etc.......
};
struct B
{
double B_data;
char B_data_2;
// etc.......
};
I want the function can access different member variables depends on different struct
passing to T
,so I wrote such code:
template<typename T>
std::string EncodeData(int DataType, T Data, std::string ReadCommandID, std::string& ThisID)
{
if(std::is_same<T, A>{})
{
// Do something with Data.A_data and Data.A_data_2
}
else if(std::is_same<T, B>{})
{
// Do something with Data.B_data and Data.B_data_2
}
// other code.
}
And use it:
A data={100,false};
std::string id;
std::string result = EncodeData<A>(0,data,"read_id_xxxxxxxx",id);
But when I compile it, the following error happened:
error C2039: "B_data": is not a member of "A".
error C2039: "B_data_2": is not a member of "A".
How can I fix this? Or what else I can do to solve this problem in one single function?
P.S. I'm using MSVC Compiler(Visual Studio 2019)