2

Nstd::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。 当然,这个问题是你不能以这种方式重载构造函数。

任何想法?

回答

4

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

Demo

+0

你能解释一下吗? – 0x499602D2 2014-10-11 15:38:25

+0

@ 0x499602D2 OP中的一个重新定义了相同的函数模板(使用不同的默认参数)。使签名的'enable_if'部分成为这两个不同的函数模板。 – 2014-10-11 15:42:18

+0

那么前者应该用于SFINAE吗? – 0x499602D2 2014-10-11 15:51:31