gpt4 book ai didi

c++ - 尝试将 std::make_unique 声明为我的模板类的友元时 MSVC 出错

转载 作者:搜寻专家 更新时间:2023-10-30 23:55:03 24 4
gpt4 key购买 nike

显然今天,MSVC 正在尽最大努力说服我改用 clang。但我不会放弃。之前我问过this question想知道如何申报std::make_unique作为friend我类的。

我在我的简单场景中得到了一个很好的答案,事实上当我在 wandbox 上用 clang 尝试它时它编译得很好。

所以我很高兴回到 Visual Studio 2013 继续编码。我的部分代码是这样的:

// other includes
#include <string>
#include <memory>

template <typename Loader, typename Painter, typename MeshT>
class Model
{
public:
friend std::unique_ptr<Model> std::make_unique<Model>(
const std::string&,
const std::shared_ptr<Loader>&,
const std::shared_ptr<Painter>&);

// Named constructor
static std::unique_ptr<Model> CreateModel(
const std::string& filepath,
const std::shared_ptr<Loader>& loader,
const std::shared_ptr<Painter>& painter)
{
// In case of error longer than the Lord of the Rings trilogy, use the
// line below instead of std::make_unique
//return std::unique_ptr<Model>(new Model(filepath, loader, painter));
return std::make_unique<Model>(filepath, loader, painter);
}

// ...
protected:
// Constructor
Model(
const std::string& filepath,
const std::shared_ptr<Loader>& loader,
const std::shared_ptr<Painter>& painter)
: mFilepath(filepath)
, mLoader(loader)
, mPainter(painter)
{
}

// ...

};

好吧,老实说,我没想到会在第一次就做对,但我相信我可以从错误消息中理解一些道理:

1>d:\code\c++\projects\active\elesword\src\Model/Model.hpp(28): error C2063: 'std::make_unique' : not a function
1> ..\..\src\Main.cpp(151) : see reference to class template instantiation 'Model<AssimpLoader,AssimpPainter,AssimpMesh>' being compiled

显然,MSVC 并不认为 std::make_unique 函数是..嗯..函数。

最糟糕的是我很累,我觉得我错过了一些非常非常(...)明显的东西。任何人都可以帮助我摆脱困境吗?

此外,任何人都可以使用 Visual Studio 2015 尝试这个吗?只是出于好奇..

注意:我知道我可以(而且可能应该)只使用 return std::unique_ptr<Model>(new Model(filepath, loader, painter));但就是感觉不对。

最佳答案

尝试与 std 函数交 friend 会使您处于危险境地,因为您正在对标准无法保证的实现做出假设。例如,您希望 std::make_unique 成为友元以便它可以访问您的 protected 构造函数,但是如果 std::make_unique 的实现将其委托(delegate)给其他 secret 函数怎么办?然后你需要做的是与那个 secret 函数成为 friend ,但它是 secret 的,所以你不能。

其他并发症:某些形式的 std::make_unique 并没有完全按照标准指定(尽管我认为这不适用于这个确切的例子)。在编译器完全支持可变参数模板之前,旧版本的 VC++ 使用宏魔术来模拟可变参数模板,因此虽然有 std::make_unqiue,但它可能没有您期望的实际签名。

关于c++ - 尝试将 std::make_unique 声明为我的模板类的友元时 MSVC 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33905782/

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