C++ C++;11:可变模板功能参数的数量?
如何获得可变模板函数的参数数计数 即:C++ C++;11:可变模板功能参数的数量?,c++,c++11,variadic-templates,variadic-functions,C++,C++11,Variadic Templates,Variadic Functions,如何获得可变模板函数的参数数计数 即: 模板 空f(常数T和…T) { int n=参数的个数(t); ... } 实现上述参数数量的最佳方法是什么?只需写下以下内容: const std::size_t n = sizeof...(T); //you may use `constexpr` instead of `const` 请注意,n是一个常量表达式(即在编译时已知),这意味着您可以在需要常量表达式的地方使用它,例如: std::array<int, n> a; //
模板
空f(常数T和…T)
{
int n=参数的个数(t);
...
}
实现上述参数数量的最佳方法是什么?只需写下以下内容:
const std::size_t n = sizeof...(T); //you may use `constexpr` instead of `const`
请注意,n
是一个常量表达式(即在编译时已知),这意味着您可以在需要常量表达式的地方使用它,例如:
std::array<int, n> a; //array of n elements
std::array<int, 2*n> b; //array of (2*n) elements
auto middle = std::get<n/2>(tupleInstance);
希望有帮助。#包括
#include <iostream>
template<typename ...Args>
struct SomeStruct
{
static const int size = sizeof...(Args);
};
template<typename... T>
void f(const T&... t)
{
// this is first way to get the number of arguments
constexpr auto size = sizeof...(T);
std::cout<<size <<std::endl;
}
int main ()
{
f("Raje", 2, 4, "ASH");
// this is 2nd way to get the number of arguments
std::cout<<SomeStruct<int, std::string>::size<<std::endl;
return 0;
}
模板
结构SomeStruct
{
静态常量int size=sizeof…(Args);
};
模板
空f(常数T和…T)
{
//这是获取参数数量的第一种方法
constexpr auto size=sizeof…(T);
std::coutsizeof…(T)
@R.MartinhoFernandes“发布您的答案”表单离页面底部有几英寸远。@kay SEisevil我不明白为什么你的评论上的投票数比他的少。+1学到了两件事;sizeof…
和constexpr
:)所以这个sizeof…
实际上返回的是参数的数量,而不是所有参数的组合存储大小(比如数组上的大小)
返回压缩在T
中的类型数。如果要计算压缩类型的聚合大小,则必须执行以下操作:我在回答中也添加了此项。@panzi:我回答中的计算现在略有改进。使用C++17,要计算单个arg类型的大小,现在可以使用折叠表达式 返回(0+…+sizeof(t));
template<std::size_t ...>
struct add_all : std::integral_constant< std::size_t,0 > {};
template<std::size_t X, std::size_t ... Xs>
struct add_all<X,Xs...> :
std::integral_constant< std::size_t, X + add_all<Xs...>::value > {};
constexpr auto size = add_all< sizeof(T)... >::value;
constexpr auto size = (sizeof(T) + ...);
#include <iostream>
template<typename ...Args>
struct SomeStruct
{
static const int size = sizeof...(Args);
};
template<typename... T>
void f(const T&... t)
{
// this is first way to get the number of arguments
constexpr auto size = sizeof...(T);
std::cout<<size <<std::endl;
}
int main ()
{
f("Raje", 2, 4, "ASH");
// this is 2nd way to get the number of arguments
std::cout<<SomeStruct<int, std::string>::size<<std::endl;
return 0;
}