【发布时间】:2014-12-06 14:39:48
【问题描述】:
让N 成为std::size_t 类型的模板参数。我希望能够以两种方式调用我的类的构造函数:
A a(x1, x2, x3, ..., xN)
和
A a(x1, x2, x3, ..., xN, xN1)
其中xi 变量都是同一类型。我的第一个想法是:
template <std::size_t N>
struct A
{
template <typename ...Args, typename = typename std::enable_if<N == sizeof...(Args), void>::type>
A(Args ...args) {
f(args...); // where f is some function
}
template <typename ...Args, typename = typename std::enable_if<N+1 == sizeof...(Args), void>::type>
A(Args ...args) {
// run f on the first N arguments
// run g on the last argument (selection is done using templates, I just did not want to write the code)
}
};
此技术在以下位置进行了说明:Variadic templates with exactly n parameters。 当然,这样做的问题是不能以这种方式重载构造函数。
有什么想法吗?
【问题讨论】:
标签: c++ templates c++11 metaprogramming template-meta-programming