Building a class from variable templates

I am trying to create a class called Sinkthat will create a pointer to the class you are going to, this is the api shell in RAII.

In the full version of this code, the user class is also inherited from another class, and there are static assets for verification. The pointer is also passed to api.

But to make it simple, I deleted it.

This is the error I get from cpp.sh

 In function 'int main()':
43:30: error: no matching function for call to 'Sink<OneArg>::Sink(int)'
43:30: note: candidate is:
10:5: note: Sink<CustomSink, Args>::Sink(Args&& ...) [with CustomSink = OneArg; Args = {}]
10:5: note:   candidate expects 0 arguments, 1 provided

The code:

#include <string>
#include <iostream>
#include <memory>
#include <utility>

template<typename CustomSink, typename... Args>
class Sink
{
public:
    Sink(Args&&... args)
    {        
       _ptr = std::make_unique<CustomSink>(std::forward<Args>(args)...);        
    }
    ~Sink() 
    {
    }
private:
    std::unique_ptr<CustomSink> _ptr;
};


//////////////////////////////////////////////////////////////////////
class NoArg
{
public:
    NoArg() {};
    ~NoArg() {};
};

class OneArg
{
public:
    OneArg(int a) {
        std::cout << a << '\n';
    };
    ~OneArg() {};
};
//////////////////////////////////////////////////////////////////////


int main(){
    Sink<NoArg> noArgSink;   
    Sink<OneArg> oneArgSink(5);  

    return 0;
}
+4
source share
4 answers

Your problem here is the layout of the template type Args. You have Argstempalte in the class right now , so

Sink<OneArg> oneArgSink(5);

, Args , Sink . , Args , .

template<typename... Args>
Sink(Args&&... args)
{        
   _ptr = std::make_unique<CustomSink>(std::forward<Args>(args)...);        
}

, , , .

+5

:

template<typename CustomSink>
class Sink
{
public:
    template <typename... Args>
    Sink(Args&&... args)
    {        
       _ptr = std::make_unique<CustomSink>(std::forward<Args>(args)...);        
    }
private:
    std::unique_ptr<CustomSink> _ptr;
};
+5

:

Sink<OneArg, int> oneArgSink(5);

, (typename ... Args). , . .

, , (. Jarod42 answer NathanOliver one)

+3

Sink , Args... .

, Sink<OneArg>, Args... , . .

. , .

template<typename CustomSink>
class Sink
{
public:
    template<typename... Args>
    Sink(Args&&... args)
    {
        _ptr = std::make_unique<CustomSink>(std::forward<Args>(args)...);
    }
    ~Sink()
    {
    }
private:
    std::unique_ptr<CustomSink> _ptr;
};
+1
source

Source: https://habr.com/ru/post/1676476/


All Articles