如何仅在复制构造函数存在时调用它? C++

How to call a copy constructor only if it exist ? c++

我正在制作一个实体-组件-系统引擎,但我在使用预制件时遇到了一些麻烦。我想复制一个预制件,前提是用户传递的 class 模板是可复制构造的。我想要做的事情的简单实现将是这样的:

void addFromPrefab() { //We assume that _prefab is of type std::shared_ptr<T>
    if (std::is_copy_constructible<T>::value)
        addComponent(*_prefab); // Add a new component by copy constructing the prefab passed as parameter
    else if (std::is_default_constructible<T>::value)
        addComponent(); // Add a new component with his default constructor
    else
        throw std::exception();
}

template<typename ...Args>
void addComponent(Args &&...args) {
    store.emplace_back(std::make_shared<T>(args ...));
}

有没有办法让这段代码正常工作?实际上,它让我无法创建特定的 class 因为它是一个可复制构造的构造函数已被删除(就是这种情况)。

提前致谢,对于我的错误我很抱歉我是法国人 ;)

如果你有 C++17,请使用 if constexpr:

void addFromPrefab() { //We assume that _prefab is of type std::shared_ptr<T>
    if constexpr(std::is_copy_constructible<T>::value)
        addComponent(*_prefab); // Add a new component by copy constructing the prefab passed as parameter
    else if constexpr(std::is_default_constructible<T>::value)
        addComponent(); // Add a new component with his default constructor
    else
        throw std::exception();
}

如果不这样做,则必须使用 SFINAE:

std::enable_if<std::is_copy_constructible<T>::value> addFromPrefab() { //We assume that _prefab is of type std::shared_ptr<T>
    addComponent(*_prefab); // Add a new component by copy constructing the prefab passed as parameter
}
std::enable_if<!std::is_copy_constructible<T>::value && std::is_default_constructible<T>::value> addFromPrefab() {
    addComponent(); // Add a new component with his default constructor
}

std::enable_if<!std::is_copy_constructible<T>::value && !std::is_default_constructible<T>::value> addFromPrefab() {
        throw std::exception();
}