C++: get const or non-const reference type from trait
- by maciekp
I am writing a functor F which takes function of type void (*func)(T) and func's argument arg. Then functor F calls func with arg. I would like F not to copy arg, just to pass it as reference. But then I cannot simply write "void F(void (*func)(T), T&)" because T could be a reference. So I am trying to write a trait, which allows to get proper reference type of T:
T -> T&
T& -> T&
const T -> const T&
const T& -> const T&
I come up with something like this:
template<typename T>
struct type_op
{
typedef T& valid_ref_type;
};
template<typename T>
struct type_op<T&>
{
typedef typename type_op<T>::valid_ref_type valid_ref_type;
};
template<typename T>
struct type_op<const T>
{
typedef const T& valid_ref_type;
};
template<typename T>
struct type_op<const T&>
{
typedef const T& valid_ref_type;
};
Which doesn't work for example for
void a(int x) { std::cout << x << std::endl; }
F(&a, 7);
Giving error:
invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’ in passing argument 2 of ‘void f(void (*)(T), typename type_op::valid_ref_type) [with T = int]’
How to get this trait to work?