C++ 参数个数不定的函数
我希望实现如下代码:C++ 参数个数不定的函数,c++,c++11,C++,C++11,我希望实现如下代码: template <typename... Args> class A { public: A(Args... args) {ind = std::make_tuple(args...);} std::tuple<Args...> ind; }; void foo() { std::cout << std::endl; } template <typename First, typename... Res
template <typename... Args>
class A
{
public:
A(Args... args) {ind = std::make_tuple(args...);}
std::tuple<Args...> ind;
};
void foo()
{
std::cout << std::endl;
}
template <typename First, typename... Rest>
void foo(First _first, Rest... _rest)
{
std::cout << _first;
foo(_rest...);
}
int main()
{
A<int, int> a1(1, 2);
A<int, int, int> a2(1, 2, 3);
A<int, int, int, int> a3(1, 2, 3, 4);
foo(a1.ind);
foo(a2.ind);
foo(a3.ind);
}
在类A中,字段ind不必是tuple,主要的是foo方法接受一组参数。在调用tuple之前,必须从tuple中解包参数 也许是这样的:
template< size_t ... Ints >
class integer_sequence{};
template < typename T, size_t N >
struct add_sequence;
template < size_t N, size_t ... IDX >
struct add_sequence< integer_sequence<IDX...>, N>
{
using type = integer_sequence< IDX..., N>;
};
template < size_t N >
struct sequence_helper
{
using type = typename add_sequence< typename sequence_helper<N-1>::type, N-1>::type;
};
template<>
struct sequence_helper<0>
{
using type = integer_sequence<>;
};
template<size_t N>
using make_integer_sequence = typename sequence_helper<N>::type;
template < typename IS, typename TUPLE >
struct call;
template < size_t ... IDX, typename ... PARMS >
struct call< integer_sequence< IDX...>, std::tuple< PARMS...>>
{
static void go( std::tuple< PARMS...> parms )
{
foo( std::get< IDX >( parms ) ... );
}
};
template < typename ... PARMS >
void foo2( std::tuple< PARMS...>& tup )
{
call<make_integer_sequence< sizeof...(PARMS)>, std::tuple< PARMS...>>::go( tup );
}
int main()
{
A<int, int> a1(1, 2);
A<int, int, int> a2(1, 2, 3);
A<int, int, int, int> a3(1, 2, 3, 4);
foo2(a1.ind);
foo2(a2.ind);
foo2(a3.ind);
}
这里的大部分代码在C++14或C++17中提供,无需自行编写。我们有2020,你应该考虑换成C++17!继续使用过时的编译器,一遍又一遍地编写所有代码是没有多大意义的。主要的是函数是通过一组参数传递的。对不起,我听不懂这句话。我可以澄清一下,谢谢。不幸的是,我不能使用C++14或C++17。