Desidero dichiarare la funzione std::make_unique
come amico della mia classe. Il motivo è che voglio dichiarare il mio costruttore protected
e fornire un metodo alternativo per creare l'oggetto usando unique_ptr
. Ecco un esempio di codice:Come rendere std :: make_unique un amico della mia classe
#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;
}
Proprio ora ottengo questo errore:
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
Qual è il modo corretto di dichiarare std::make_unique
come un amico della mia classe?
prova a compilare con clang - si lamenta: 'main.cpp: 17: 39: errore: gli amici possono essere solo classi o funzioni - amico' std :: unique_ptr > std :: make_unique >(); 'con il la posizione dell'errore è l'istanziazione del modello. – marko
È interessante notare che il compilatore con -std = C++ 14 e questo scompare, e gli errori puntano verso la risposta di @ Praetorian sotto. – marko
@marko L'errore precedente è con clang. Sono su MSVC (vs 2013) ora però. Non funziona neanche lì. – TheCrafter