如何在C++11中使用可变的非类型模板参数来解决这个问题


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, 0), translate(e2, 1))
std::make_shared<A>(translate(e3, 0), translate(e0, 1))

下面是一个使用std::integer_sequence的解决方案。这是C++14的一个特性,但到C++11的端口确实存在(没有使用过,无法保证其质量(。

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)>{});
}
};

相关内容

最新更新