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

Why can we create a template class struct with a number of parameters different from those specified when declaring a struct?

本文关键字:参数 结构 声明 包含许 我们 创建 一个 为什么      更新时间:2023-10-16

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

#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;
}

如果您添加缺少的包含#include <iostream>#include <tuple> .