gpt4 book ai didi

c++ - 具有可变参数编译问题的模板函数

转载 作者:搜寻专家 更新时间:2023-10-31 02:06:52 25 4
gpt4 key购买 nike

我不熟悉带有可变参数的模板函数。受 Codeview 文章启发的代码不在 CreateBook() 中编译,需要帮助。

我想使用工厂方法和模板创建一个对象。

using namespace std;

template<class T>
class bar
{
public:
template<class... Args>
static bar<T> CreateBook(Args&&... args)
{
return bar<T>(std::forward<Args>(args)...); // Don't compile here
}

T get()
{
return val;
}
private:

bar(const T& t) :val(t) {}
T val;

};

struct book
{
string name;
int phone;
book(string s, int t) : name(s), phone(t) {}
};

void print(bar<book> k)
{
cout << k.get().name << " " << k.get().phone << endl;
}

int main()
{
bar<book> b = bar<book>::CreateBook("Hello World",91520);

print(b);

return 0;
}

最佳答案

请参阅此代码。您的 bar 构造函数也应该处理 pack 参数。

template<class... X>
bar(X... x) :val(x...) {}

关于c++ - 具有可变参数编译问题的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49595525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com