0

I got stuck implementing my own template class where I wanted to add my own implementation of emplace_back function. 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. It only works with no arguments. How should I fix this?

sebap123
  • 2,541
  • 6
  • 45
  • 81

3 Answers3

8

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

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;
};
Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
3

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. You will need to use std::forward.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
0

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...

Biggy Smith
  • 910
  • 7
  • 14