【问题标题】:How to call a copy constructor only if it exist ? c++仅当复制构造函数存在时如何调用它? C++
【发布时间】:2018-11-20 22:48:21
【问题描述】:

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

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 ...));
}

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

在此先感谢,并为我的错误道歉,我是法国人;)

【问题讨论】:

  • 你会用 C++17 吗?
  • 是的,我已经用这个版本编译了。

标签: c++ templates constructor variadic-functions copy-constructor


【解决方案1】:

如果你有 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();
}

【讨论】:

    猜你喜欢
    • 2017-02-08
    • 2011-07-17
    • 2019-08-12
    • 2018-10-17
    • 2016-12-09
    • 2013-04-17
    • 2013-06-12
    • 1970-01-01
    相关资源
    最近更新 更多