gpt4 book ai didi

c++ - 为什么此代码在模板特化方面有错误

转载 作者:行者123 更新时间:2023-11-28 01:47:03 25 4
gpt4 key购买 nike

我想使用一个函数将参数传递给不同的类,所以我使用了类模板特化和可变函数模板,下面是代码:

#include <iostream>
using namespace std;

template <typename T0, typename T1>
class Package
{
T0 Data0;
T1 Data1;
public:
Package(T0 data0, T1 data1): Data0(data0), Data1(data1) {}
void Display()
{
cout << Data0 << " " << Data1 << endl;
}
};

template <typename T0>
class Package<T0, void>
{
T0 Data0;
public:
Package(T0 data0): Data0(data0) {}
void Display()
{
cout << Data0 << endl;
}
};

template <>
class Package<void, void>
{
public:
Package() {}
void Display()
{
cout << "have no member" << endl;
}
};

template <typename... Args>
void Post(Args... args)
{
Package<Args...> pak = Package<Args...>(args...);
pak.Display();
}

int main()
{
int x = 5;
float y = 0.9;
Post(x, y);
Post(x);
Post();
return 0;
}

我有这个错误:

 In instantiation of 'void Post(Args ...) [with Args = {int}]': 
52:15: required from here
43:26: error: wrong number of template arguments (1, should be 2)
5:11: error: provided for 'template<class T0, class T1> class Package'
43:26: error: wrong number of template arguments (1, should be 2)
5:11: error: provided for 'template<class T0, class T1> class Package'
In instantiation of 'void Post(Args ...) [with Args = {}]':
53:14: required from here
43:26: error: wrong number of template arguments (0, should be 2)
5:11: error: provided for 'template<class T0, class T1> class Package'
43:26: error: wrong number of template arguments (0, should be 2)
5:11: error: provided for 'template<class T0, class T1> class Package'

package可以带2/1/0个参数,post可以提供2/1/0个参数,但是为什么会出现这个错误?谢谢。

最佳答案

尝试将默认模板参数添加到 Package

template <typename T0 = void, typename T1 = void>
class Package

关于c++ - 为什么此代码在模板特化方面有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44642573/

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