Tôi đang sử dụng GCC 4.8 để biên dịch đoạn mã sau:Tại sao tôi gặp lỗi biên dịch?
#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
}
bất cứ ai có thể giải thích cho tôi lý do của lỗi này từ trình biên dịch?
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)...});
^
Tôi không muốn làm cho các nhà thầu công khai. Đây là lý do tại sao tôi đã giới thiệu tạo(), Hơn nữa, đối với một số lý do chỉ số S() xây dựng tư nhân không làm cho biên soạn thất bại khi nó tư nhân, trong khi S (int) làm cho việc biên soạn thất bại ... – Martin