为什么我们可以创建一个模板类结构,其结构参数与声明结构时指定的参数不同?

时间:2019-07-14 19:36:07

标签: c++

我在Internet上的某处看到了这段代码,您能告诉我为什么可以编译它吗? 据我所知,如果您在模板中指定的参数计数不正确-应该是编译错误,不是吗?

#include <iostream>
#include <tuple>
template<typename F, typename Tuple, bool Enough, int TotalArgs, int... N>
struct call_impl
{
    auto static call(F f, Tuple&& t)
    {
        //This line
        return call_impl<F, Tuple, TotalArgs == 1 + sizeof...(N),
            TotalArgs, N..., sizeof...(N)>::call(f, std::forward<Tuple>(t));
    }
};

template<typename F, typename Tuple, int TotalArgs, int... N>
struct call_impl<F, Tuple, true, TotalArgs, N...>
{
    auto static call(F f, Tuple&& t)
    {
        return f(std::get<N>(std::forward<Tuple>(t))...);
    }
};

template<typename F, typename Tuple>
auto call(F f, Tuple&& t)
{
    typedef typename std::decay<Tuple>::type type;
    return call_impl<F, Tuple, 0 == std::tuple_size<type>::value,
        std::tuple_size<type>::value
    >::call(f, std::forward<Tuple>(t));
}

int foo(int i, double d)
{
    std::cout << "foo: " << i << " " << d << std::endl;
    return i;
}

int main()
{
    std::tuple<int, double> t1(1, 2.3);
    std::cout << call(foo, t1) << std::endl;
}

1 个答案:

答案 0 :(得分:0)

如果添加缺少的#include <iostream>,则此compiles fine#include <tuple>