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表达式调用宏,然后在我的库代码中获得它的类型。
发布于 2019-03-22 11:07:29
首先,如果你想将Drawable传递给GetVTable,你必须将绘图标记为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 functional。
由于您的返回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; \
}当然,你可以去掉helper函数,直接把它写在auto的地方。
https://stackoverflow.com/questions/55289047
复制相似问题