1

理想情况下,我想声明以下类型:

using action_t = std::function< std::vector< action_t >(void) >

这是一个 thunk,它返回一个后续 thunk 的向量。我能够使用来自Recursive typedef 函数定义的信息来做到这一点: std::function 返回它自己的类型

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 直接推送到它上面。

有没有办法做到这一点?

4

1 回答 1

2

编写一个构造函数,该构造函数接受任何可转换为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.

于 2015-04-09T04:02:31.823 回答