小编mac*_*ekp的帖子

模板仿函数不能推导出引用类型

我有一个仿函数f,它接受函数func和与func相同类型的参数t.由于编译错误(调用没有匹配函数),我无法将g传递给f f(int&, void (&)(int&)).如果g将采用非引用参数g(int s),则编译完成.或者,如果我手动指定模板参数f<int&>(i, g),编译也会完成.

template<typename T>
void f(T t, void (*func)(T)) {}

void g(int& s) {}

int main(int, char*[])
{
    int i = 7;

    f(i, g); // compilation error here

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得演绎?

c++ templates reference functor

4
推荐指数
3
解决办法
1447
查看次数

从trait中获取const或非const引用类型

我正在编写一个函子F,它接受类型为void(*func)(T)和func的参数arg的函数.

template<typename T>
  void F(void (*func)(T), WhatTypeHere? arg)
{
  func(arg);
}
Run Code Online (Sandbox Code Playgroud)

然后,仿函数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&
Run Code Online (Sandbox Code Playgroud)

我想出这样的事情:

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)
{ …
Run Code Online (Sandbox Code Playgroud)

c++ templates reference traits functor

3
推荐指数
1
解决办法
2135
查看次数

标签 统计

c++ ×2

functor ×2

reference ×2

templates ×2

traits ×1