par*_*iad 3 c++ templates metaprogramming template-meta-programming c++11
让N成为 type 的模板参数std::size_t。我希望能够以两种方式为我的类调用构造函数:
A a(x1, x2, x3, ..., xN)
Run Code Online (Sandbox Code Playgroud)
和
A a(x1, x2, x3, ..., xN, xN1)
Run Code Online (Sandbox Code Playgroud)
其中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)
}
};
Run Code Online (Sandbox Code Playgroud)
该技术在以下位置进行了解释:具有恰好 n 个参数的可变模板。当然,这样做的问题是您不能以这种方式重载构造函数。
有任何想法吗?
只是 SFINAE 不同:
template <std::size_t N>
struct A
{
template <typename ...Args,
typename std::enable_if<N == sizeof...(Args), int>::type = 0>
A(Args ...args) {
}
template <typename ...Args,
typename std::enable_if<N+1 == sizeof...(Args), int>::type = 0>
A(Args ...args) {
}
};
Run Code Online (Sandbox Code Playgroud)
演示。