有的时候我们需要在构建对象时注入一系列类型不确定的对象或插件,怎么才能实现呢?
#include <iostream>
#include <string>
#include <tuple>
using namespace std;
class A{
public:
A(int a) : m_a(a)
{
cout<<"construct A:"<<m_a<<endl;
}
int m_a;
};
class B{
public:
B(string s) : m_s(s)
{
cout<<"construct B:"<<m_s<<endl;
}
string m_s;
};
class C{
public:
C()
{
cout<<"construct C"<<endl;
}
double m_d{3.14};
};
template<typename T, typename Tuple>
struct has_type;
template<typename T, typename U, typename... Ts> //如果tuple的第一个类型U不是T,弹出U,递归调用has_type。比如T的类型是B时, Ts是<A, B>,所以先解包Ts为A和Ts=<B>,递归调用has_type
struct has_type<T, tuple<U, Ts...>> : has_type<T, tuple<Ts...>>
{
};
template<typename T, typename... Ts>