gpt4 book ai didi

c++ shared_ptr with std::function or double (*SOME_NAME)(double);

转载 作者:太空宇宙 更新时间:2023-11-04 14:09:01 25 4
gpt4 key购买 nike

Q1) 鉴于我们有

typedef double (*function_t)(double);

typedef std::function<double(double)> function_t;

我们如何定义

std::shared_ptr<function_t> ptr_func = ???

为了某些功能。

假设我们想要一个 shared_ptr到一个已经定义的对象(暂时忘记它违背了目的 - 但我需要这个)。作为示例,考虑以下类型的对象 double .

struct null_deleter
{
void operator() (void const *) const {};
};

int main()
{
// define object
double b=0;

// define shared pointer
std::shared_ptr<double> ptr_store;
ptr_store.reset(&b,null_deleter()); // this works and behaves how you would expect
}

虽然如果我们对 shared_ptr 做同样的事情类型 function_t ,即

double f (double x)
{
// some_function + return
}

int main()
{

// define shared pointer
std::shared_ptr<function_t> ptr_store;
ptr_store.reset(&f,null_deleter()); // ERROR: does not work
}

返回的错误类似于以下内容:

error: cannot convert 'double (*)(double)' to 'double (**)(double)' in initialization

或者在 std::function 的情况下

error: cannot convert 'double (*)(double)' to 'std::function<double(double)>*' in initialization

很明显没有传递正确的类型,可能我们不允许这样做(?)

注意:用g++4-7-2编译带有 -std=c++11 -O3 的版本在 Windows MinGW 上

几个答案都很好,我会在今天的某个时候回复大家。现在是早上 6 点 30 分,我还没睡呢。我正在实现的整个设计模式可能是错误的,希望我稍后能解释一下:|

最佳答案

这是人为设计的,但这是我在不了解您实际尝试做的事情的情况下所能想到的最好的方法:

#include <iostream>

typedef std::function<double(double)> function_t;

double f(double t)
{
return t*5;
}

int main(int argc, char*argv[])
{
// You usually want to attach the shared pointer to a dynamically allocated object
std::shared_ptr<function_t> ptr;
ptr.reset(new function_t(std::bind(&f, std::placeholders::_1)));
std::cout << (*ptr)(5.0);

// But we can attach the smart pointer to a local function object on the stack (BAD IDEA)
function_t fff = std::bind(&f, std::placeholders::_1);
ptr.reset(&fff);
std::cout << (*ptr)(5.0);
}

关于c++ shared_ptr with std::function or double (*SOME_NAME)(double);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15652149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com