所以我一直在尝试更多地理解可变参数模板,我的目标是接收所有类型,扩展它们并打印它们。我能够在一个函数中做到这一点(找到一些例子)但我不是能够为班级做到这一点我正在尝试构建一个“主人”来容纳许多“奴隶”,每个奴隶都应该从他那里继承一个 Slave_T 然后知道它的类型,并将其打印在 c'tor 上。
但由于某种原因,我无法修复模棱两可的编译错误。我试图避免将任何类型作为参数传递给函数。我尝试使用 enable_if 或 true/false_type 约定但无法,任何人都有任何想法? 这是我的代码:(包括功能扩展)
有效的功能扩展:
template<typename T, typename... Targs>
void Print(T value, Targs... Fargs) // recursive variadic function
{
Print<T>();
Print(Fargs...); // recursive call
}
template<typename T>
void Print(T = NULL)
{
std::cout << typeid(T).name() << endl;
}
我需要帮助的类扩展:
#include <iostream>
#include <vector>
#include <type_traits>
#include <memory>
using namespace std;
struct Slave {
virtual char const* Type() = 0;
};
template<typename T>
struct Slave_T : public Slave{
virtual char const* Type() {
return typeid(T).name();
}
};
template <typename ...T>
struct Master {
Master()
{
MakeSlave<T...>();
cout << "All Slaves:" << endl;
for (auto const& slave : v){
cout << slave ->Type() << endl;
}
}
private:
template<typename T, typename ...Rest>
void MakeSlave()
{
MakeSlave<Rest...>(); MakeSlave<T>();
}
template<typename T>
void MakeSlave() {
v.push_back(new Slave_T<T>());
}
vector<shared_ptr<Slave>> v;
};
int main()
{
Master<int, double, char> m;
//Print("Hello", '!', 123, 123);
return 0;
}
谢谢!
阿隆