C 函子初始化

C++ functor initialization

本文关键字:初始化      更新时间:2023-10-16

我无法在以下代码示例中理解 {}的目的。为什么不做cell_type(...)而不是cell_type{}(...)?我只是在这里放了一个简化的版本,希望显示足够的上下文。原始代码位于https://github.com/pytorch/pytorch/blob/master/master/aten/src/aten/native/rnnn.cpp#l781,以防万一您想要更多信息。

#define DEFINE_QUANTIZED_RNN_CELL(..., cell_type, ... ) 
    ...
    # what's the purpose of {} in the following line?   
    return cell_type{}(                                  
       ...);                                            
}
using quantized_lstm_cell_type = LSTMCell<QuantizedCellParams>;
DEFINE_QUANTIZED_RNN_CELL(..., quantized_lstm_cell_type, ...);
template <typename cell_params>
 struct LSTMCell {
   using hidden_type = std::tuple<Tensor, Tensor>;
   hidden_type operator()(...) const override {
      ...
   }
};

cell_type{}构建了cell_type的临时实例。假设cell_type公开了operator(),则需要一个实例来调用它 - 因此,您不能简单地说cell_type()。例如

struct cell_type { void operator()() { } };
cell_type{}(); // OK, creates temporary instance and invokes it
cell_type();   // Creates temporary instance, but doesn't invoke it

我的猜测是DEFINE_QUANTIZED_RNN_CELL期望类型而不是实例,这就是为什么它使用{}