为什么我们可以创建一个模板类结构,其中包含许多与声明结构时指定的参数不同的参数
Why can we create a template class struct with a number of parameters different from those specified when declaring a struct?
我在互联网上的某个地方看到了这段代码,你能告诉我为什么它可以编译吗?据我所知,如果您在模板中指定了不正确的参数计数 - 应该有编译错误,不是吗?
#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>
.
相关文章:
- 使用不带参数的函数访问结构元素
- 将结构字段的类型展开为可变模板参数
- MSVC将仅移动结构参数解释为指针
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 如何传递带有通过引用传递的结构参数的函数?
- 展开可变参数模板结构
- 在类构造函数中定义结构变量的参数
- 如何在方法中传递结构参数
- 我应该在C++中将这些结构用作参数化构造函数吗?
- 带参数的数据结构的全局声明
- C++ 带有默认参数的结构,可选择在构造函数中更改
- C++-将具有引用的长参数列表重构为结构
- 为私有结构定义双参数运算符重载
- 我们可以用参数化构造函数初始化结构的数组吗?
- 关于类的想法 参数结构给定实现
- 重映射模板参数结构
- 从C 调用的编译MATLAB函数的输入参数结构
- 如何实现具有不同参数结构的纯虚拟函数
- 如何在C++中获得可更改的函数参数结构
- 函数参数 -> 结构体成员的 void* 和常量 void* 的解决方案