64,686
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <vector>
// 需要封装的功能
class GetVectorVal
{
public:
GetVectorVal(const std::vector<double>& vec)
: m_vec(vec), m_index(0)
{
}
template <typename T>
T get_val()
{
return (T)m_vec[m_index++]; // 实际系统中这里会有复杂的参数类型验证和装换操作
}
private:
const std::vector<double>& m_vec;
int m_index;
};
template <typename... ArgsType>
void vector_call(const std::vector<double>& args, int(*func)(ArgsType...))
{
GetVectorVal ArgGetter(args);
func(ArgGetter.get_val<ArgsType>()...); //!! 这里 get_val 改变了状态, 依赖于编译器的参数求值顺序
}
// 各式各样的 C++ 函数对象, 测试用
int print1(int x)
{
printf("%d\n", x);
return 1;
}
int printfloat(float x)
{
printf("%.4f\n", x);
return 1;
}
int print3(int x, int y, int z)
{
printf("%d %d %d\n", x, y, z);
return 1;
}
// 测试
int main()
{
std::vector<double> args = { 10.341, 20, 30, 40, 50 };
vector_call(args, print1);
vector_call(args, printfloat);
vector_call(args, print3);
}
ArgsType... realargs = ArgGetter.get_val<ArgsType>()...;
func(realargs...);
template<class T, size_t N> void f( T (&array)[N])
{
for (int i = 0; i < N; ++i)
cout << array[i] << endl;
}
int main()
{
double a[] = { 10.341, 20, 30, 40, 50 };
f(a);
return 0;
}
虽然没看懂 但是不知道这个代码对你是否有帮助
template <typename... ArgsType, size_t... Index>
void vector_call_imp(const std::vector<double>& args, int(*func)(ArgsType...), std::index_sequence<Index...>)
{
GetVectorVal gv(args);
func(gv.get_val<ArgsType>(Index)...);
}
template <typename... ArgsType>
void vector_call(const std::vector<double>& args, int(*func)(ArgsType...))
{
vector_call_imp(args, func, std::make_index_sequence<sizeof...(ArgsType)>());
}
#include <stdio.h>
#include <tuple>
void func( int a, double b, const char* c )
{
printf( "%d\t%f\t%s\n", a, b, c );
}
template<class F, class T , size_t... I>
void invoke_impl( F f, T t, std::index_sequence<I...> )
{
f( std::get<I>( t )... );
}
template<class F, class... T >
void invoke( F f, T... t )
{
invoke_impl( f, std::make_tuple( t... ) , std::make_index_sequence<sizeof...( T )>() );
}
int main()
{
invoke( func , 1, 2.0, "ccc" );
}
标准库也提供了std::invoke
std::tuple<ArgsType...> t;
auto l = std::make_index_sequence<sizeof...(ArgsType)>();
func(std::get<l>(t)...); // error C3546: '...': there are no parameter packs available to expand