Reputation: 498
I currently have this macro
#define bind(OBJECT, ROLE) \
assert( sizeof(*ROLE) == 1 ); \
ROLE = reinterpret_cast<decltype(ROLE)>(OBJECT);
It is causing some name clashing issues so I'd like to move this into a templated function like
template<typename T1, typename T2>
void bind(T1 obj, T2 r) {
assert( sizeof(*r) == 1 );
r = reinterpret_cast<T2>(obj);
};
However, I suspect that this is not possible, but would like to be confirmed on this? In order to change r, I must have a pointer to a pointer?
Upvotes: 1
Views: 148
Reputation: 283793
You will need at least need a reference:
template<typename T1, typename T2>
void bind(T1 obj, T2& r)
{
assert( sizeof(*r) == 1 );
r = reinterpret_cast<T2>(obj);
}
Another option is to use a template conversion operator. Then you can call with the syntax:
ROLE = bind(OBJ);
The code would be more-or-less like this:
template<typename T1> class auto_converter
{
const T1& value;
public:
auto_converter(const T1& v) : value(v) {}
// template conversion operator
template<typename T2>
operator T2() const
{
assert(sizeof (*T2()) == 1);
return reinterpret_cast<T2>(value);
}
};
template<typename T1>
autoconverter<T1> bind(const T1& obj) { return obj; }
Upvotes: 3
Reputation: 28767
Declare r as reference in order to change it:
template<typename T1, typename T2>
void bind(T1 obj,
T2 &r) //<-- here
{
assert( sizeof(*r) == 1 );
r = reinterpret_cast<T2>(obj);
};
Upvotes: 2