c++ - 在一个变量中保存两种不同的返回类型

标签 c++ c++11

在下面的代码中,我想用params来保存两种不同的返回类型。所以我可以删除冗余代码。但是,我这里没有好的解决方案。

我的版本:

if (...) { 
    auto params = gather_quantized_params(_params);
    // the following lines are just duplicated in different branches 
    auto results = _lstm_impl<FullLayer, FullBidirectionalLayer>(
        input, params, hx[0], hx[1], num_layers, dropout_p, train, bidirectional); 

   return results;
} else {
    auto params = gather_quantized_params_fp16(_params);
    auto results = _lstm_impl<FullLayer, FullBidirectionalLayer>(
        input, params, hx[0], hx[1], num_layers, dropout_p, train, bidirectional);
    return results 
}

=== 相关函数头:

    static std::vector<QuantizedCellParamsFP16> 
gather_quantized_params_fp16(TensorList params) {
    ...}

  static std::vector<QuantizedCellParams> 
    gather_quantized_params(TensorList params) { 
    ...} 

template<template<typename,typename> class LayerT, 
  template<typename,typename> class BidirLayerT, 
  typename cell_params, typename io_type> 
std::tuple<io_type, Tensor, Tensor> _lstm_impl(
         const io_type& input,
         const std::vector<cell_params>& params, const Tensor& hx, const Tensor& cx,
         int64_t num_layers, double dropout_p, bool train, bool bidirectional) { ...} 

=== 当我使用答案中建议的方法时(这真的很酷),我遇到了以下错误 - “错误:在 lambda 参数声明中使用'auto'仅适用于 -std=c++14 或 -std= gnu++14”。

似乎我需要另一种解决方案来避免在 lambda 参数中使用 auto。

最佳答案

我建议这样做:

auto implement_params = [&](auto params) {
    auto results = _lstm_impl<FullLayer, FullBidirectionalLayer>(
        input, params, hx[0], hx[1], num_layers, dropout_p, train, bidirectional); 

   return results;
}; 

if(...) {
    return implement_params(gather_quantized_params(_params));
} else {
    return implement_params(gather_quantized_params_fp16(_params));
}

关于c++ - 在一个变量中保存两种不同的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57119913/

相关文章:

c++ - 如何简单地从小端格式的缓冲区中重建数字

c++ - IntelliSense 无法打开源文件

c++ - std::get 在右值引用元组上的行为是否危险?

c++ - 如何在创建和对象时初始化类内的二维数组

c++ - 无法弄清楚为什么我的 str2Int 函数返回 0

c++ - Windows API 作业对象 : Don't pass on to grandchildren

c++ - 将整数转换为指针总是定义良好吗?

c++ - 将转换范围缩小到更大的类型(然后再返回)

c++ - 无法从C++中的抽象类绑定(bind)函数

c++ - 我可以在编译时检查成员函数是否是运算符吗?