Why variadic template constructor matches better than copy constructor?

前端 未结 3 1057
灰色年华
灰色年华 2021-01-11 20:49

The following code does not compile:

#include 
#include 

struct Foo
{
    Foo() { std::cout << \"Foo()\" << std::         


        
3条回答
  •  伪装坚强ぢ
    2021-01-11 21:28

    Another way to avoid the variadic constructor being selected is to supply all forms of the Bar constructor.

    It's a little more work, but avoids the complexity of enable_if, if that's important to you:

    #include 
    #include 
    
    struct Foo
    {
        Foo() { std::cout << "Foo()" << std::endl; }
        Foo(int) { std::cout << "Foo(int)" << std::endl; }
    };
    
    template 
    struct Bar
    {
        Foo foo;
    
        Bar(const Bar&) { std::cout << "Bar(const Bar&)" << std::endl; }
        Bar(Bar&) { std::cout << "Bar(Bar&)" << std::endl; }
        Bar(Bar&&) { std::cout << "Bar(Bar&&)" << std::endl; }
    
        template 
        Bar(Args&&... args) : foo(std::forward(args)...)
        {
            std::cout << "Bar(Args&&... args)" << std::endl;
        }
    };
    
    int main()
    {
        Bar bar1{};
        Bar bar2{bar1};
    }
    

提交回复
热议问题