C++ std::function returns 它自己类型的向量(又是递归类型)
C++ std::function that returns a vector of it's own type (recursive types again)
理想情况下,我想声明以下类型:
using action_t = std::function< std::vector< action_t >(void) >
这是一个 thunk,returns 后续 thunk 的向量。我能够使用来自 Recursive typedef function definition : std::function returning its own type 的信息得到这么远:
struct RecursiveHelper
{
typedef std::vector<RecursiveHelper> rtype;
typedef std::function< rtype (void) > ftype;
RecursiveHelper( ftype f ) : func(f) {}
rtype operator()() const { return func(); }
operator ftype () { return func; }
ftype func;
};
using action_t = RecursiveHelper;
using actions_t = std::vector<RecursiveHelper>;
但是,例如,要将这些东西压入堆栈,我必须这样做:
std::stack<action_t> stack;
stack.push(RecursiveHelper([&visitor, &node](void){
return visitor.visitNode(node);
}));
理想情况下,我想避免在使用这些东西的代码中提及 RecursiveHelper
,如果他们想要一堆 action_t,他们应该能够将符合要求的 lambda 直接推到上面.
有什么办法可以做到吗?
编写一个构造函数,接受任何可转换为 ftype
而不是 RecursiveHelper
的函数对象:
template<class F, class = std::enable_if_t<std::is_convertible<F, ftype>::value &&
!std::is_same<RecursiveHelper, std::decay_t<F>>::value>>
RecursiveHelper( F&& f ) : func(std::forward<F>(f)) {}
对于 C++11,将 something_t<...>
替换为 typename something<...>::type
。
理想情况下,我想声明以下类型:
using action_t = std::function< std::vector< action_t >(void) >
这是一个 thunk,returns 后续 thunk 的向量。我能够使用来自 Recursive typedef function definition : std::function returning its own type 的信息得到这么远:
struct RecursiveHelper
{
typedef std::vector<RecursiveHelper> rtype;
typedef std::function< rtype (void) > ftype;
RecursiveHelper( ftype f ) : func(f) {}
rtype operator()() const { return func(); }
operator ftype () { return func; }
ftype func;
};
using action_t = RecursiveHelper;
using actions_t = std::vector<RecursiveHelper>;
但是,例如,要将这些东西压入堆栈,我必须这样做:
std::stack<action_t> stack;
stack.push(RecursiveHelper([&visitor, &node](void){
return visitor.visitNode(node);
}));
理想情况下,我想避免在使用这些东西的代码中提及 RecursiveHelper
,如果他们想要一堆 action_t,他们应该能够将符合要求的 lambda 直接推到上面.
有什么办法可以做到吗?
编写一个构造函数,接受任何可转换为 ftype
而不是 RecursiveHelper
的函数对象:
template<class F, class = std::enable_if_t<std::is_convertible<F, ftype>::value &&
!std::is_same<RecursiveHelper, std::decay_t<F>>::value>>
RecursiveHelper( F&& f ) : func(std::forward<F>(f)) {}
对于 C++11,将 something_t<...>
替换为 typename something<...>::type
。