采用类对象的模板函数是否可以使用其构造函数参数实例化该对象?
Can a template function taking class object instantiate that object with it's constructors arguments?
假设我有一个接受类对象的模板函数:
template<class T>
void Foo(T obj);
以及如下的类定义:
class Bar
{
public:
Bar(int a, bool b): _a(a), _b(b) {}
private:
int _a;
bool _b;
};
有没有办法编译以下代码?
Foo<Bar>(5,false);
Foo<Bar>({5,false}); // i know this works, just wondering if i can remove the brackets somehow.
是的,这可以通过可变模板和转发来完成,并且有许多标准示例,如std::make_unique
。
在您的情况下,它将是:
template<class T, class ...Args>
void Foo(Args &&...args)
{
T obj { std::forward<Args>(args)... };
// use obj
}
相关文章:
- 类中的 Arduino 对象构造函数设置垃圾值
- 编译错误:临时对象构造函数中缺少参数
- 双指针在使用 new 时不调用对象构造函数
- 以支持继承的方式将自身shared_ptr添加到对象构造函数中的向量中
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数
- GCC __attribute__((constructor)) 在对象构造函数之前调用
- 自定义对象构造函数在循环外部循环
- 从全局对象构造函数停止监视器计时器
- Arduino 上的 Sketch 停止在对象构造函数中执行
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 为什么当对象构造函数投入新表达式时,为什么不调用DealLocation函数
- 临时结构对象构造函数奇数调用
- 未显式引用对象的全局对象构造函数在最终二进制文件 - LD 中被丢弃
- 为什么 Clang++ 不在另一个静态库中运行全局对象构造函数?
- 在未加载上下文的情况下在对象构造函数中使用OpenGL函数
- 为什么我们需要一个用户提供的const对象构造函数
- 对象构造函数的C++数组
- 将子结构值设置为对象构造函数中安全的纯虚拟函数返回的值
- C等价于新对象(构造函数)
- C++:直接在参数列表中使用数组文字的对象构造函数