2
让N
为std::size_t
类型的模板参数。我想能够调用我的类的构造函数有两种方式:变量参数(包的大小为N)和默认参数
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。 当然,这个问题是你不能以这种方式重载构造函数。
任何想法?
你能解释一下吗? – 0x499602D2 2014-10-11 15:38:25
@ 0x499602D2 OP中的一个重新定义了相同的函数模板(使用不同的默认参数)。使签名的'enable_if'部分成为这两个不同的函数模板。 – 2014-10-11 15:42:18
那么前者应该用于SFINAE吗? – 0x499602D2 2014-10-11 15:51:31