【发布时间】:2016-02-27 13:34:21
【问题描述】:
我想将std::make_unique 函数声明为我班级的朋友。原因是我想声明我的构造函数protected 并提供另一种使用unique_ptr 创建对象的方法。这是一个示例代码:
#include <memory>
template <typename T>
class A
{
public:
// Somehow I want to declare make_unique as a friend
friend std::unique_ptr<A<T>> std::make_unique<A<T>>();
static std::unique_ptr<A> CreateA(T x)
{
//return std::unique_ptr<A>(new A(x)); // works
return std::make_unique<A>(x); // doesn't work
}
protected:
A(T x) { (void)x; }
};
int main()
{
std::unique_ptr<A<int>> a = A<int>::CreateA(5);
(void)a;
return 0;
}
现在我收到此错误:
Start
In file included from prog.cc:1:
/usr/local/libcxx-head/include/c++/v1/memory:3152:32: error: calling a protected constructor of class 'A<int>'
return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...));
^
prog.cc:13:21: note: in instantiation of function template specialization 'std::__1::make_unique<A<int>, int &>' requested here
return std::make_unique<A>(x); // doesn't work
^
prog.cc:22:41: note: in instantiation of member function 'A<int>::CreateA' requested here
std::unique_ptr<A<int>> a = A<int>::CreateA(5);
^
prog.cc:17:5: note: declared protected here
A(T x) { (void)x; }
^
1 error generated.
1
Finish
将std::make_unique 声明为我班的朋友的正确方法是什么?
【问题讨论】:
-
尝试使用 clang 编译 - 它抱怨:
main.cpp:17:39: error: friends can only be classes or functions - friendstd::unique_ptr> std::make_unique>();` 错误位置是模板实例化。 -
有趣的是,带有 -std=c++14 的编译器和这个消失了,错误指向下面@Praetorian 的答案。
-
@marko 上述错误与 clang 有关。我现在在 MSVC(与 2013 年相比)。那里也不行。
-
好的。我的坏 - 不同的标准版本。除了这个技巧很难实现之外,我质疑这作为一种合同设计 - 看起来你在这里混淆而不是分离关注点。
-
我同意这个建议,因为它依赖于实现并且你不能依赖它工作。可能是重新设计的时候了:/
标签: c++ templates c++14 unique-ptr friend-function