common type-erasure libraries都是C ++ 14或C ++ 17。因为我坚持使用C ++ 11,所以我想写自己的。问题是我无法使下面的代码工作:
struct Drawable {
void draw() const { poly_call<0>(*this); }
//How has this macro to look like?
MAKE_VTABLE([](T const& self) { self.draw(); })
};
//My library-code:
using VTableForT = decltype(Drawable::GetVTable<T>());
为了澄清,在C ++ 14中它可能看起来像:
#define MAKE_VTABLE(lambda) \
template<class T> \
static auto GetVTable() { \
return lambda; \
}
但是C ++ 11中还没有自动返回功能。有任何想法吗?对我而言,GetVTable是静态函数还是静态变量无关紧要。我只是想让用户使用他的lambda表达式调用宏,然后在我的库代码中获取它的类型。
首先,如果你想将Drawable传递给GetVTable,你必须将draw标记为const,因为参数标记为const(在返回的lambda中),我们只能调用const标记的函数。
现在来看实际问题。你有什么要求?你是否一定想从GetVTable返回lambda或者另一个Callabe呢?从函数中返回lambda总是很乱。可能的解决方法来自使用std :: function
返回类型将成为std::function <void(T const&)>
因此代码看起来像:
#define MAKE_VTABLE(lambda) \
template<class T> \
static std::function<void(T const&)> GetVTable() { \
return lambda; \
}
请记住#include功能。
由于返回lambda不捕获任何内容,因此它也可以转换为裸函数指针。
// A helper using declaration for return type
template <class T>
using ret_t = void (*) (T const&);
// The macro
#define MAKE_VTABLE(lambda) \
template<class T> \
static ret_t<T> GetVTable() { \
return lambda; \
}
当然,您可以取消辅助函数并将其直接写入auto的位置。