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