Sto usando GCC 4.8 per compilare il codice seguente:Perché ricevo un errore di compilazione?
#include <memory>
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique(Args&& ...args) {
return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
}
struct S {
template<class... Args>
static std::unique_ptr<S> create(Args&&... args) {
return make_unique<S>(std::forward<Args>(args)...);
}
private: // if I remove this line, then the compilation is OK
S(int) {}
S() = default;
};
int main() {
auto s1 = S::create(); // OK
auto s2 = S::create(0); // Compilation error
}
Qualcuno mi può spiegare il motivo di questo errore del compilatore?
main.cpp: In instantiation of 'std::unique_ptr make_unique(Args&& ...) [with T = S; Args = {int}]':
main.cpp:11:58: required from 'static std::unique_ptr S::create(Args&& ...) [with Args = {int}]'
main.cpp:20:26: required from here
main.cpp:14:5: error: 'S::S(int)' is private
S(int) {} ^
main.cpp:5:65: error: within this context return std::unique_ptr(new T{std::forward(args)...});
^
Non voglio rendere pubblici i costruttori. Questo è il motivo per cui ho introdotto create(), Inoltre, per alcuni motivi il costruttore privato S() non fa fallire la compilazione quando è privata, mentre S (int) fa fallire la compilazione ... – Martin