[英]Add emplace_back to template class
I got stuck implementing my own template class where I wanted to add my own implementation of emplace_back
function. 我在实现自己的模板类时陷入困境,我想在其中添加自己的
emplace_back
函数实现。 Since I am still learning template design I'll appreciate your input here. 由于我仍在学习模板设计,因此在这里感谢您的投入。
template <typename T, typename ...Args>
class MydataStruct
{
public:
//...
void emplace_back(Args&&... args)
{
//...
myqueue.emplace_back(args...);
}
//...
private:
std::deque<T> myqueue;
};
Sample use: 样品使用:
MydataStruct<int> test;
test.emplace_back(1);
Whenever I am trying to compile this code I receive error that emplace_back is not defined. 每当我尝试编译此代码时,都会收到未定义emplace_back的错误。 It only works with no arguments.
它仅在没有参数的情况下起作用。 How should I fix this?
我该如何解决?
You should make the member function a member function template . 您应该使成员函数成为成员函数模板 。 Use variadic Forwarding References to capture the arguments, then
std::forward
the arguments to myqueue.emplace_back
使用可变参数的转发引用来捕获参数,然后将
std::forward
参数传递到myqueue.emplace_back
template <typename T>
class MydataStruct
{
public:
//...
template<typename ...Args>
void emplace_back(Args&&... args)
{
//...
myqueue.emplace_back(std::forward<Args>(args)...);
}
//...
private:
std::deque<T> myqueue;
};
The error is that you put your variadic template in your class' template parameters rather than add one to your method. 错误是您将可变参数模板放在类的模板参数中,而不是在方法中添加一个。 Try this instead.
试试这个吧。
#include <deque>
template <typename T /*typename ...Args*/>
// remove this ^^^^^^^^^^^^^^^^^
class MydataStruct
{
public:
//...
template<typename ...Args>
// add this ^^^^^^^^^^^^^
void emplace_back(Args&&... args)
{
myqueue.emplace_back(args...);
}
private:
std::deque<T> myqueue;
};
int bop()
{
MydataStruct<int> test;
test.emplace_back(1);
}
Edit: Note that this will not do what you want with rvalues. 编辑:请注意,这将不会对rvalues起到作用。 You will need to use std::forward .
您将需要使用std :: forward 。
to get your example to work you would have to do 要使您的榜样发挥作用,您就必须做
MydataStruct<int,int> test;
test.emplace_back(1);
but moving the ...Args to the emplace_back function is the way to go... 但是将... Args移至emplace_back函数是解决方法...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.