c++ - 如何仅在复制构造函数存在时调用它?由 小码哥发布于

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

我正在制作一个实体组件系统引擎,但我在预制件方面遇到了一些问题。我想复制预制件,前提是用户传递的模板具有可复制构造的类。我想做的事情的简单实现如下:

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,请使用 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();
}

关于c++ - 如何仅在复制构造函数存在时调用它?由 小码哥发布于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53402751/

相关文章:

templates - 根据模板参数选择参数类型

c++ - 切换模板类型

constructor - 如何在 Flutter 中更改 slider 标签颜色?

c++ - 命令提示符 "runas user:<admin-user> <command>"未正确执行

c# - 空对象与空对象

c++ - 如何在源文件中对模板函数进行专门化?

java - 在两个构造函数中初始化最终变量

C++ - 创建安全的 const char* 构造函数

c++ - 使用 C++ sql.h 备份 SQL 数据库

c++ - 从基指针列表循环 (OOD) 调用派生类方法