将复杂函数变量作为参数传递 [英] Passing a complex function variants as arguments

查看:140
本文介绍了将复杂函数变量作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下模板函数:

template <class T>
void apply(const vector<complex<T> >& in, vector<T>& out, T (*f)(complex<T>))
{
    out.resize(in.size());
    for(size_t i = 0; i < in.size(); ++i) out[i] = f(in[i]);
}

你可以看到,我只想将一个函数应用到一个复杂的数据,并将结果存储到实际数据的向量中。我想这应该是一个完整的功能列表:abs,norm,real,imag等。

You can see, I just want to apply a function to a vector of complex data, and store the results into a vector of real data. I figure this should be good for a whole list of function: abs, norm, real, imag, etc.

我的问题是,如何传递一个函数?

My problem is, how do I pass a function in?

我尝试过的变体apply(in,out,abs) > abs 没有运气。我很确定的问题源于复杂的所有模板的功能,但我不知道如何正确传递它。感谢您的帮助。

I have tried variants of apply(in, out, abs) supplying different templates to abs with no luck. I am pretty sure the problem stems from the functions for complex all being templates, but I am not sure how to pass it properly. Thanks for the help.

推荐答案

问题是 std :: abs < complex> )将 std :: complex< T> 参数作为参考 - const。您的函数指针只通过值说明,这会导致不匹配。以下代码编译得很好:

The problem is that std::abs (from <complex>) takes the std::complex<T> parameter as a reference-to-const. Your function pointer only says by value, which causes the mismatch. The following code compiles just fine:

#include <vector>
#include <complex>

template <class T>
void apply(const std::vector<std::complex<T> >& in, std::vector<T>& out,
           T (*f)(std::complex<T> const&))
{
    out.resize(in.size());
    for(size_t i = 0; i < in.size(); ++i)
      out[i] = f(in[i]);
}

int main(){
  std::vector<std::complex<float> > vcomp;
  std::vector<float> vf;
  apply(vcomp, vf, &std::abs<float>);
}

在Ideone上的实例。

然而,更好的想法是简单地将函数类型作为模板参数: p>

A better idea, however, would be to simply take the function type as a template parameter:

template <class T, class F>
void apply(const std::vector<std::complex<T> >& in, std::vector<T>& out, F f)
{
    out.resize(in.size());
    for(size_t i = 0; i < in.size(); ++i)
      out[i] = f(in[i]);
}

在Ideone上的现场示例。

在任何情况下,您有时可能需要在调用网站上使用转换是模板重载的(我不记得一个从< complex> 函数,但你永远不知道) p>

In any case, you sometimes might need to disambiguate at the call site with a cast, if a function is templated and overloaded (I don't remember one off-hand from the <complex> functions, but you never know).

// taking std::abs as an example. It's not actually templated *and* overloaded
typedef float (*func_ptr)(std::complex<float> const&);
apply(vcomp, vf, (func_ptr)&std::abs<float>);

这篇关于将复杂函数变量作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆