How can I prevent a variadic constructor from being preferred to the copy constructor?

前端 未结 4 1827
生来不讨喜
生来不讨喜 2020-12-13 14:09

I have a template \'Foo\', which owns a T, and I\'d like it to have a variadic constructor that forwards its arguments to T\'s constructor:

template

        
4条回答
  •  天命终不由人
    2020-12-13 14:16

    You can use some ugly SFINAE with std::enable_if, but I'm not sure it is better than your initial solution (in fact, I'm pretty sure it's worse!):

    #include 
    #include 
    
    // helper that was not included in C++11
    template using disable_if = std::enable_if;
    
    template
    struct Foo {
    
        Foo() = default;
        Foo(const Foo &) = default;
    
        template::type,
                    Foo
                >::value
            >::type
        >
        Foo(Arg&& arg, Args&&... args)
            : t(std::forward(arg), std::forward(args)...) {}
    
        T t;
    };
    
    int main(int argc, char* argv[]) {
        Foo> x(new int(42));
        decltype(x) copy_of_x(x);
        decltype(x) copy_of_temp(Foo>(new int));
        return 0;
    }
    

提交回复
热议问题