如何在std :: function中存储std :: sqrt [英] How to store std::sqrt in std::function

查看:70
本文介绍了如何在std :: function中存储std :: sqrt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: sqrt() 的类型为 std :: complex< T(const std :: complex< T&).为什么不能将其存储在此 std :: function 中?我得到的错误是:

std::sqrt() is of type std::complex<T>(const std::complex<T>&). Why can't I store it in this std::function? The error I get is:

错误:请求从"转换为非标量类型"std :: function(const std :: complex&)>"

error: conversion from ‘’ to non-scalar type ‘std::function(const std::complex&)>’ requested

在此处运行:

#include <complex>
#include <functional>
#include <iostream>

int main(){
    using Complex = std::complex<double>;
    std::function<Complex(const Complex&)> f = std::sqrt;
    std::cout << "sqrt(4): " << f(std::complex<double>(4,0)) << "\n";
    return 0;
}

推荐答案

关于代码中的行:

std::function<Complex(const Complex&)> f = std::sqrt;

您必须考虑到 std :: sqrt() 不是普通功能,而是功能模板:

template<class T>
complex<T> sqrt(const complex<T>& z);

您根据 std :: complex 类模板:

You defined Complex in terms of the std::complex class template:

using Complex = std::complex<double>;

因为 std :: complex 包含与传递的 template参数相对应的成员类型 value_type (即,在这种情况下 double ),您可以执行以下操作:

Since std::complex contains the member type value_type that corresponds to the passed template argument (i.e., double in this case), you can just do:

std::function<Complex(const Complex&)> f = std::sqrt<Complex::value_type>;

这等效于将 double 作为模板参数直接传递给 std :: sqrt():

This is equivalent to directly passing double as template argument to std::sqrt():

std::function<Complex(const Complex&)> f = std::sqrt<double>;

但是,前者比后者更通用,因为它允许您更改 std :: complex 的模板参数-例如,使用 int 浮动而不是 double –无需编辑与分配相对应的源代码.

However, the former is more generic than the latter because it allows you to change std::complex's template argument – e.g., using int or float instead of double – without having to edit the source code corresponding to the assignment.

自C ++ 14起,您还可以通过通用lambda 将对包装的调用包装到 std :: sqrt()并将此lambda分配给std :: function 对象:

Since C++14 you can also wrap the call to std::sqrt() by means of a generic lambda and assign this lambda to the std::function object:

std::function<Complex(const Complex&)> f = [](auto const& x) { 
   return std::sqrt(x); 
};

这篇关于如何在std :: function中存储std :: sqrt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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