我寫了我自己的「槽」又名「可調用包裝器」,因爲我想在其他對象上提供成員函數槽rebinding(即我需要一種方法來存儲成員函數指針和指向所討論的類的指針)。我的插槽類錯過std :: function有什麼功能?
我跑了一個小尺寸的測試,發現我的系統(64位Linux)上的std::function
是我自己實現類似類的三倍(Clang/libC++)的兩倍(GCC/libstdC++),帶有大小爲16字節。對於非成員函數和lambda的實現是這樣(的const void*
第一個參數是與這裏沒有顯示的成員函數插槽均勻性):
template<typename... ArgTypes>
class slot
{
public:
virtual ~slot() = default;
virtual void operator()(const void* object, ArgTypes...) const = 0;
protected:
slot() = default;
};
template<typename Callable, typename... ArgTypes>
class callable_slot : public slot<ArgTypes...>
{
public:
callable_slot(Callable function_pointer_or_lambda) : callable(function_pointer_or_lambda) {}
virtual void operator()(const void*, ArgTypes... args) const override { callable(args...); }
private:
Callable callable;
};
template<typename Callable>
class callable_slot<Callable> : public slot<>
{
public:
callable_slot(Callable function_pointer_or_lambda) : callable(function_pointer_or_lambda) {}
virtual void operator()(const void*) const override { callable(); }
private:
Callable callable;
};
template<typename Callable, typename... ArgTypes>
using function_slot = callable_slot<Callable, ArgTypes...>;
我理解一些target
這裏沒有實現,但我不認爲任何缺失的函數都會增加對象的大小。
我在問的是:爲什麼std::function
的尺寸比我上面的便宜實現大?
'的std :: function'有一個小目標優化 – Brian