mercredi 30 septembre 2015

Casting char to int reference in a template

I am trying to write a serialization function, as a part of which, I need to convert char to int, and leave other types unchanged. I have written the following code:

template<typename T1>
struct return_type {typedef T1 type;};
template<>
struct return_type<char> {typedef int type;};

template<typename T1>
typename return_type<T1>::type &type_transform(T1 &&t) 
{ 
    //If writing/reading char, cast it to int
    return static_cast<typename return_type<T1>::type &>((t));
} 

The idea is to be able to write

ofstream f1;
......
f1<<type_transform(variable);
f1<<type_transform(func());

and

ifstream f1;
......
f1>>type_transform(variable);

Where variable/function could be any variable or function. But I keep getting an error saying invalid cast from char to int&, when I try using char type. Could somebody please explain?

Aucun commentaire:

Enregistrer un commentaire