我正在研究一个小的小型测试类,它将使用一个函数/函数来执行,而函数/函数会生成对该函数的输入来执行。
例如,如果第一个函数是第一个函数sqrt(x)
,而第二个函数有一个状态并且正在计数,我希望该类执行
sqrt(0.0);
sqrt(1.0);
...
对于一些迭代。
我可以相对容易地做到这一点(2 std::function
s或模板),但是如果第一个函数接受多个参数,该如何实现呢?我只能想到强制一个函数采用tuple
,而强制另一个函数返回tuple
,但这看起来很丑陋,并在测试的函数上强制使用接口。
编辑:我现在所拥有的:
template <typename Func, typename ArgGen>
class Magic
{
std::function<double (time_t)> time_to_frequency;
std::set<decltype(Func()(ArgGen()()))> results_ok;
std::set<decltype(Func()(ArgGen()()))> results_fail;
ArgGen ag;
Func f;
public:
Magic(std::set<decltype(Func()(ArgGen()()))> results_ok, std::set<decltype(Func()(ArgGen()()))> results_fail, std::function<double (const time_t)> time_to_frequency) :
results_ok(results_ok), results_fail(results_fail), time_to_frequency(time_to_frequency)
{}
Magic()
{}
void run(const int n)
{
bool success=true;
for (int i=0; i< n; ++i)
{
auto rv = f(ag());
const bool result_ok = results_ok.count(rv);
if (result_ok)
{
printf(".");
}
else
{
success = false;
std::cout << i <<": value unexpected "<< std::endl;
}
}
std::cout << "run succeeded: " << std::boolalpha << success;
}
};
我将让ArgGen返回一个元组,然后使用以下命令打开该元组的包装:
#include <tuple>
#include <iostream>
template <class Func, class ... Args>
struct invoke_from_tuple_helper
{
typedef decltype(std::declval<Func>()(std::declval<Args>()...)) return_type;
template <unsigned total, std::size_t ... Indices>
static return_type apply_helper(Func && f, std::tuple<Args...> && params,
typename std::enable_if<total == sizeof...(Indices)>::type* =NULL)
{
return f(std::forward<Args>(std::get<Indices>(params))...);
}
template <unsigned total, std::size_t ... Indices>
static return_type apply_helper(Func && f, std::tuple<Args...> && params,
typename std::enable_if<(total > sizeof...(Indices)) >::type* =NULL)
{
return apply_helper<
total, Indices..., sizeof...(Indices)>
(std::forward<Func>(f), std::forward<std::tuple<Args...> >(params));
}
static return_type apply(Func && f, std::tuple<Args...> && params)
{
return apply_helper<sizeof...(Args)>(std::forward<Func>(f),
std::forward<std::tuple<Args...> >(params));
}
};
template <class Func, class ... Args>
typename invoke_from_tuple_helper<Func,Args...>::return_type
invoke_from_tuple(Func && f, std::tuple<Args...>&¶ms)
{
return invoke_from_tuple_helper<Func,Args...>::apply(std::forward<Func>(f),
std::forward<std::tuple<Args...> >(params));
}
void f(int, long, std::tuple<int,long>)
{
std::cout << "I'm on the inside\n";
}
int main()
{
invoke_from_tuple(f, std::tuple<int,long,std::tuple<int,long> >());
return 0;
}
这是使用g ++-4.8编译并运行的
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句