问题描述
enum Enum
{
e0,e1,e2
};
int translate(Enum e)
{
//...
}
int translate(Enum e,int index)
{
//...
}
class A
{
public:
template<typename... Ts>
A(Ts... ts)
{
//...
}
};
template<Enum... es>
class B
{
public:
static std::shared_ptr<A> getA()
{
//for example,use "int translate(Enum e)"
//return std::make_shared<A>(translate(es)...);
//use "int translate(Enum e,int index)" "index" like the index in "for(int index = 0; index < n; ++index)"
//how to writer?
}
};
这是关于可变参数非类型模板参数;我想用C ++ 11来解决它。
例如:
std::make_shared<A>(translate(e1,0),translate(e2,1),translate(e3,2)) std::make_shared<A>(translate(e1,1)) std::make_shared<A>(translate(e3,translate(e0,1))
解决方法
这是使用std::integer_sequence
的解决方案。这是C ++ 14的功能,但可以移植到C ++ 11 do exist(尚未使用过,无法保证其质量)。
template<Enum... es>
class B
{
template <int... Is>
static std::shared_ptr<A> getAHelper(std::integer_sequence<Is...>) {
return std::make_shared<A>(translate(es,Is)...);
}
public:
static std::shared_ptr<A> getA()
{
return getAHelper(std::make_integer_sequence<sizeof...(es)>{});
}
};