gpt4 book ai didi

c++ - C++ 中类似 QuickCheck 的模板函数基准测试

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:22 27 4
gpt4 key购买 nike

受到 Haskell 自动生成(随机)给定类型实例的优雅方式的启发,例如在 QuickCheck 中,我正在尝试弄清楚如何编写一个 as-easy-to-use-as-可能的 C++ 基准测试框架。我想我将使用函数模板,可能会借助 C++11 中的新功能,例如可变参数模板。我希望我只需要指定一个函数或更好的函数模板和一个与函数的参数兼容的 STL 模板容器类型(反过来它的 value_type)。

我认为,使用一组不同大小的输入对函数进行基准测试有点类似于 C++11 中线程的设置和生成方式。我的第一个尝试是复制 thread 类的构造函数并将其转换为 benchmark 函数作为

template< class Function, class ...Args >
inline
void benchmark( Function&& f, Args&&... args );

我不确定我们是否应该在这里使用右值引用。但是,fargs 必须在调用 benchmark 之前显式实例化,导致 无法正常使用

这导致我尝试跳过调用参数而只使用模板参数:

namespace pnw
{
template <template <typename> class Function, typename Container>
inline
void benchmark_container()
{
Function<typename Container::iterator> f;
Container c(10);
f(c.begin(), c.end());
}
}

称为

typedef int T;
typedef std::vector<T> C;
pnw::benchmark_container<std::sort, C>();

但是,现在编译错误为

tests/t_histogram.cpp: In function ‘void test_benchmark()’:
tests/t_histogram.cpp:56:44: error: no matching function for call to ‘benchmark_container()’
tests/t_histogram.cpp:56:44: note: candidate is:
tests/../benchmark.hpp:32:6: note: template<template<class> class Function, class Container> void pnw::benchmark_container()

我不确定 C++ 是否可以仅通过另一个调用函数的模板参数来处理传递函数模板。

这是正确的方法还是在 C++11 中不可能?我正在使用 GCC-4.6。

最佳答案

如果你需要支持“higher-kinded”参数,你必须使用template-template parameters .此外,在模板内,如果 typename 未限定,f::g 将被视为一个值。因此你应该写:

template <template <typename> class Function, typename Container>  // <--
inline void benchmark_container()
{
Function<typename Container::iterator> f; // <--
...

(所有这些都在 C++11 之前可用。)


编辑但是电话

benchmark_container<std::sort, C>();

不会工作,因为 std::sort 是一个重载的模板函数,而不是类模板。您也不能单独引用 std::sort,因为它会产生歧义。

如果你只想使用像 std::sort 这样没有关联上下文的函数,你可以传递一个函数指针来消除重载的歧义:

template <typename Container,
void (*func)(typename Container::iterator, typename Container::iterator)>
inline void benchmark_container()
{
Container c (10);
func(c.begin(), c.end());
}

benchmark_container<std::vector<int>, std::sort>();

template <typename Container>
inline void benchmark_container(void (*func)(typename Container::iterator, typename Container::iterator))
{
Container c (10);
func(c.begin(), c.end());
}

benchmark_container<std::vector<int>>(std::sort);

或者只是手动选择你想使用的重载,允许传递通用函数对象:

template <typename Container, typename F>
inline void benchmark_container(const F& function)
{
Container c (10);
function(c.begin(), c.end());
}

benchmark_container<std::vector<int>>(std::sort<std::vector<int>::iterator>);

关于c++ - C++ 中类似 QuickCheck 的模板函数基准测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8895350/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com