Ich bin mit 4.8 GCC den folgenden Code zu kompilieren:Warum erhalte ich einen Kompilierungsfehler?
#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
}
Kann mir jemand erklären, den Grund dieses Fehlers vom Compiler?
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)...});
^
Ich möchte die Konstrukteure nicht veröffentlichen. Deshalb habe ich create() eingeführt. Desweiteren macht der private S() - Konstruktor aus irgendwelchen Gründen die Kompilierung nicht fehlgeschlagen, wenn sie privat ist, während S (int) die Kompilierung fehlschlägt ... – Martin