小编m.t*_*cey的帖子

基于unique_ptr参数指针类型的重载函数

我的印象是unique_ptr可以以与普通指针相同的方式推断类层次结构,但是当我尝试重载这样的函数时:

void func(unique_ptr<Derived1>& d1);
void func(unique_ptr<Derived2>& d2);
Run Code Online (Sandbox Code Playgroud)

然后调用这样的函数之一:

unique_ptr<Base> b = make_unique<Derived1>();
func(b);    
Run Code Online (Sandbox Code Playgroud)

我收到一个错误说no instance of overloaded function "func" matches the argument list。b 的运行时类型是Derived1,所以我预计会调用第一个重载。

此外,当我unique_ptr从函数返回 a 时,编译器能够将派生类(?不确定合适的术语)转换为基类,以便像这样工作:

unique_ptr<Base> create(){
    return make_unique<Derived1>();
}
Run Code Online (Sandbox Code Playgroud)

通常在我的代码中,我将变量声明为这样的函数的结果。它们被声明为基类,但具有派生的运行时类型,我想将它们传递给一个重载函数。

我如何以与使用涉及类层次结构的常规指针相同的方式重载函数?

c++ overloading hierarchy unique-ptr

4
推荐指数
1
解决办法
61
查看次数

传递包装为 unique_ptr C++ 的“this”

我有一个类充当二叉树中的节点,我想从该类内部调用的方法之一是递归的,并且需要将自身传递给树中的下一个节点,以便下一个节点知道它的自己的父母。我不想存储类成员父级,因为我想避免使用 shared_ptr。

代码如下所示:

void MyClass::expand(MyClass* parent){
    for (int i = 0; i < children.size; i ++){
        children[i]->doSomethingWithParent(parent);
        children[i]->expand(this);
    }
    return;
}
Run Code Online (Sandbox Code Playgroud)

但我想传递一个 unique_ptr 而不是原始指针。但是,指向“this”的指针已经被 unique_ptr 包裹在其他地方,所以我不想实例化另一个。是否有可能做到这一点?

如果有任何我应该知道的设计模式,请告诉我。

任何帮助表示赞赏

c++ recursion unique-ptr

0
推荐指数
1
解决办法
72
查看次数

即使在配置 ASP.NET Core Web API 中启用了 CORS,CORS 也会阻止发布请求

我正在尝试向我的 Web API 发出简单的发布请求,但收到 CORS 错误:

\n
\n

跨源请求被阻止:同源策略不允许读取 https://localhost:5001/expression/add 处的远程资源。(原因:根据 CORS 预检响应中的标头 \xe2\x80\x98Access-Control-Allow-Headers\xe2\x80\x99,不允许使用标头 \xe2\x80\x98content-type\xe2\x80\x99)。

\n
\n

请求如下:

\n
export async function sendPostRequest(request, object) {\n\n    try {\n\n        const response = await fetch(request, {\n            method: \'POST\',\n            headers: {\n                \'Content-Type\': \'application/json\'\n            },\n            body: JSON.stringify(object),\n        });\n\n        const result = await response.json();\n\n        return result;\n\n    } catch (error) {\n        console.error(error);\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

传入该函数的url和对象如下:

\n
var url = \'https://localhost:5001/expression/add\';\n\nvar toSave = {\n    \'userId\': 1,\n    \'expression\': \'hello\'\n};\n
Run Code Online (Sandbox Code Playgroud)\n

这是端点:

\n
[ApiController]\n[Route("[controller]")]\npublic class ExpressionController : ControllerBase\n{\n    [HttpPost]\n    [Route("add")]\n …
Run Code Online (Sandbox Code Playgroud)

c# http cors .net-core

0
推荐指数
1
解决办法
2933
查看次数

标签 统计

c++ ×2

unique-ptr ×2

.net-core ×1

c# ×1

cors ×1

hierarchy ×1

http ×1

overloading ×1

recursion ×1