模板类型构造函数参数
Template type constructor parameters
给定模板类:
template<class T>
class Foo
{
public:
void FunctionThatCreatesT()
{
_object = new T;
}
private:
shared_ptr<T> _object;
}
是否有可能以某种方式将T的一组构造函数参数传递给Foo(可能是在构造Foo时),以便Foo在创建T时可以使用它们?仅使用c++ 11的解决方案就可以了(例如,变量在表中)。
正是,可变模板和通过std::forward
的完美转发。
#include <memory>
#include <utility>
template<class T>
class Foo
{
public:
template<class... Args>
void FunctionThatCreatesT(Args&&... args)
{
_object = new T(std::forward<Args>(args)...);
}
private:
std::shared_ptr<T> _object;
}
有关其工作原理的列表,请参阅这个出色的回答。
您可以在c++ 03中使用许多重载函数模拟此限制版本,但是…
同样,这只是来自内存,所以没有完成测试。
相关文章:
- C++:使用运算符 = 调用多参数构造函数
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 好奇的混合与可变参数构造函数
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 为什么我们需要创建一个单参数构造函数来使用临时的无名称对象
- 在可变参数构造函数中初始化常量数组
- C++ 显式多参数构造函数歧义
- 零一参数构造函数
- 可变参数构造函数中的 SFINAE
- 当没有显式关键字与单参数构造函数一起使用时,编译器可以发出警告
- 可变参数类模板和可变参数构造函数
- 确保模板参数类型与其可变参数构造函数的类型匹配
- C++默认参数构造函数与内联初始化优先级
- 如何在 c++ 中将包含复制构造函数的类的参数构造函数称为私有?
- 自动存储中没有无参数构造函数的类对象和异常
- 警告:用两个参数构造函数返回对象时,表达结果未使用
- 如何在C++中调用无参数构造函数
- 在 c++ 中具有多个参数构造函数的模板类存在问题
- 可变参数构造函数优先于用户提供的移动构造函数,除非默认
- 如何从可变参数构造函数参数构造任何对象?