我有一个特例,我想测量一下我的std :: function用法的统计数据。通常会花费时间,调用量,经常调用哪个函数,有时也会进行测试,例如随机抛出nullptr来检查我的代码如何处理它。
首先,我考虑从std :: func继承,然后覆盖检索指针的函数 - 或者像这样 - 但在阅读了几个主题和指南后,我得出结论,它是非常缺乏的。
我的第二个想法是简单地创建一个包装类。重构我的整个代码以使用这个包装而不是std :: function并不难,所以没关系。我想避免的是使用不必要的和不舒服的用法,就像任何额外的功能一样。例如。:
std::function<...> dummyvar (...);
// Later I can call this dummy var as simply as dummyvar(...)
// I don't want to add extra complexity, like this:
CustomWrapper<...> customdummy (...);
customdummy.getVal()(...);
// Best would be if I could actually "simply" replace all std::function to the Custom Wrapper.
在我目前非常简单的情况下,不会复制std :: function,只需简单地初始化一次,必要时一直调用它。因此,如果它有帮助你可以考虑到这一点而忽略其他东西,比如复制构造函数等等(当然,自定义实现不是缺少它的更多功能就更好了,但我亲自提到的就足够了)
我不知道如何进展,这就是我甚至没有附加任何源代码的原因。
你可以这样做:
template <typename Sig>
class CustomWrapper
{
private:
std::function<Sig> f;
mutable std::size_t nbCall = 0;
// ...
public:
CustomWrapper() = default;
CustomWrapper(const CustomWrapper&) = default;
CustomWrapper(CustomWrapper&&) = default;
CustomWrapper& operator=(const CustomWrapper&) = default;
CustomWrapper& operator=(CustomWrapper&&) = default;
template <typename T,
std::enable_if_t<!std::is_same<CustomWrapper, std::decay_t<T>>::value
&& std::is_constructible<std::function<Sig>, T&&>::value, bool> = false>
CustomWrapper(T&& arg) : f(std::forward<T>(arg)){}
template <typename ... Ts,
std::enable_if_t<(sizeof...(Ts) >= 2)
&& std::is_constructible<std::function<Sig>, Ts&&...>::value, bool> = false>
CustomWrapper(Ts&& ... args) : f(std::forward<Ts>(args)...){}
template <typename ... Ts>
auto operator ()(Ts&&... args) const -> decltype(f(std::forward<Ts>(args)...))
{
++nbCall; // Statistics you want
// ...
return f(std::forward<Ts>(args)...);
}
std::size_t getNbCall() const { return nbCall; }
// ...
};
我认为这是你可以用来创建一个包装器的想法:
template <typename T>
class CustomWrapper;
template <typename Result, typename ...Args>
class CustomWrapper<Result(Args...)>
{
public:
template <typename ...SomeArgs>
CustomWrapper(SomeArgs&&... args)
: func(std::forward<SomeArgs>(args)...)
{
}
CustomWrapper(const CustomWrapper&) = default;
CustomWrapper(CustomWrapper&&) = default;
auto operator()(Args&&... args)
{
return func(std::forward<Args>(args)...);
}
private:
std::function<Result(Args...)> func;
};
void foo()
{
CustomWrapper<void(int, int)> func([](int x1, int x2) {});
func(1, 2);
}
我没有实现所有方法,但是将它作为样本添加它们非常容易。
但我还想提一下,如果你经常调用std::function
s - 最好的想法就是摆脱std::function
本身以提高性能。如果可能,请考虑切换到功能对象。
您是希望在程序发货前经常检查统计信息还是仅检查一次?如果我只建议使用profiler / coverage工具来查看引用函数的次数。
如果你需要不断的统计数据,你需要查看std :: function接口(https://en.cppreference.com/w/cpp/utility/functional/function)并为此创建新的实现 - 实现起来并不是那么难。