参数包和完美转发

问题描述 投票:0回答:1

我刚刚编写了以下简单代码,但它无法编译:

#include <iostream>
#include <string>


class Obj{
public:
    std::string name = "Name";
    std::string l_name = "LastName";
    
    template<typename P>
    Obj(P&& param): name{std::forward<P>(param)} { }
    
    friend std::ostream& operator<<(std::ostream& os, const Obj& obj);
};

std::ostream& operator<<(std::ostream& os, const Obj& obj) {
    os << obj.name << ":" << obj.l_name;
    return os;
}


void print() {
    std::cout << "}";
}

template<typename T, typename ...Args>
void print(T param, Args... args) {
    std::size_t count = sizeof...(args);
    std::cout << param;
    if ( count != 0 ) {
        std::cout << ",";
    }
    print(args...);
}

template<typename... Args>
void run(Args... args) {
    std::cout << "{";
    print(args...);
}

int main() {
    Obj obj{"obj"};
    run("1", "2", 1.3, std::string{"Some Message"}, obj);
    
    return 0;
}

我只是使用了简单的参数包和完美的转发示例,但给出了以下错误:

main.cpp: In instantiation of ‘Obj::Obj(P&&) [with P = Obj&]’:
main.cpp:49:8:   required from here
main.cpp:12:21: error: no matching function for call to ‘std::__cxx11::basic_string::basic_string()’
   12 |     Obj(P&& param): name{std::forward<P>(param)} {
...

如果我在 run 函数中不使用 obj 参数,该示例将按预期工作。

c++
1个回答
0
投票

不幸的是

template<typename P>
Obj(P&& param): name{std::forward<P>(param)} { }

太生气了,抓住

Obj(Obj&)
(这是错误的)。

您可能会删除该构造函数,或者添加额外的重载

Obj(Obj&&) = default;
Obj(Obj&) = default; // To fix the issue
Obj(const Obj&) = default;

演示

© www.soinside.com 2019 - 2024. All rights reserved.