我正在写一个函数functor F,它接受void(func)(T)和func的参数arg的函数。从trait获得const或非const引用类型
template<typename T>
void F(void (*func)(T), WhatTypeHere? arg)
{
func(arg);
}
然后functor F调用arg的func。我希望F不要复制arg,只是为了传递它作为参考。但是,我不能简单地写出“void F(void(* func)(T),T &)”,因为T可能是一个参考。所以我想写一个特性,它允许获得的T适当的引用类型:
T -> T&
T& -> T&
const T -> const T&
const T& -> const T&
我想出了这样的事情:
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;
};
template<typename T>
void F(void (*func)(T), typename type_op<T>::valid_ref_type arg)
{
func(arg);
}
其中例如不工作了
void a(int x) { std::cout << x << std::endl; }
F(&a, 7);
给错误:在通过参数2的类型从一个临时类型“INT”的“INT &”的非const引用 无效初始化'void F(void(*)(T),typename type_op :: valid_ref_type)[with T = int]'
如何让这个特征起作用?
我认为这是非常相似的这一个:http://stackoverflow.com/questions/2539361/c-template-functor-cannot-deduce-reference-type – 2010-04-17 12:25:52