小编kpx*_*894的帖子

为什么可变参数模板构造函数比复制构造函数更好?

以下代码无法编译:

#include <iostream>
#include <utility>

struct Foo
{
    Foo() { std::cout << "Foo()" << std::endl; }
    Foo(int) { std::cout << "Foo(int)" << std::endl; }
};

template <typename T>
struct Bar
{
    Foo foo;

    Bar(const Bar&) { std::cout << "Bar(const Bar&)" << std::endl; }

    template <typename... Args>
    Bar(Args&&... args) : foo(std::forward<Args>(args)...)
    {
        std::cout << "Bar(Args&&... args)" << std::endl;
    }
};

int main()
{
    Bar<Foo> bar1{};
    Bar<Foo> bar2{bar1};
}
Run Code Online (Sandbox Code Playgroud)

编译器错误告诉我编译器试图使用variadic模板构造函数而不是复制构造函数:

prog.cpp: In instantiation of 'Bar<T>::Bar(Args&& ...) [with Args = {Bar<Foo>&}; T = …
Run Code Online (Sandbox Code Playgroud)

c++ templates overload-resolution variadic-templates c++11

10
推荐指数
2
解决办法
753
查看次数