【问题标题】:Variadic template arguments passed to template function传递给模板函数的可变模板参数
【发布时间】:2015-06-11 17:08:10
【问题描述】:

我的类接受一个int 模板参数和一个int 参数包(neurons)。构造函数的目标之一是获取包中的每个参数并将类的实例添加到向量中。但是,该类将其参数作为模板参数。

我有以下代码:

template<int iCount, int... neurons>
class network {
private:
    std::vector<pl> layers;
public:
    network() : layers() {
        input_layer<iCount> inp;
        layers.push_back(inp);
        addLayer<iCount, neurons...>();
    }
    template<int prev, int nc, int... further>
    void addLayer() {
        layer<nc, prev> l;
        layers.push_back(l);
        addLayer<nc, further...>(); // error is here
    }
};

标有“错误在这里”的递归调用会产生编译器错误:“错误 4 错误 C2783: 'void network::addLayer(void)' : could not推导出 'nc' 的模板参数"

pl 是 input_layer 和 layer 的父类。

目前,我像这样使用network:

network<1, 3,2,1> n;

调用构造函数后,我预计 n.layers 将包含四个元素。第一个是input_layer,传递给iCount,剩下的是layers,neurons中的相应条目作为它的nc,前一层的nc作为它的prev .

【问题讨论】:

标签: c++ templates


【解决方案1】:

首先,你有object slicing,所以你想要:

std::vector<std::unique_ptr<pl>> layers;

接下来,我们可以在一个函数中做到这一点而无需任何递归:

network() : layers() {
    layers.push_back(std::make_unique<input_layer<iCount>>());
    addLayers<iCount, neurons...>(std::make_index_sequence<sizeof...(neurons)>());
}

template <int... Pack, size_t... Is>
void addLayers(std::index_sequence<Is...> )  {
    static constexpr int array[] = {Pack...};

    int unused[] = {0,
        (layers.push_back(std::make_unique<layer<array[Is+1],array[Is]>>()), 0)...
    };
    (void)unused;
}

这个解决方案的灵感来自 T.C. 的回答 here。

【讨论】:

  • 我在 Visual Studio 中找不到 make_index_sequence 的包含文件。
  • @Jack 在&lt;utility&gt;。如果 VC 没有它,那么这里会发布各种实现。例如,this question
  • Visual Studio 不支持您使用的constexpr。有什么替代方案?
  • @Jack 快速破解是template&lt;size_t Index, int...Is&gt; using at_t = std::tuple_element_t&lt;Index, std::tuple&lt;std::integral_constant&lt;int, Is&gt;...&gt;&gt;;,然后使用at_t&lt;Is+1, Pack...&gt;::value 而不是array[Is+1]。
【解决方案2】:

您可以使用标签调度来填充向量:

#include <iostream>
#include <vector>

template<int... neurons>

class network {
public:
    std::vector<int> layers;

private:
    template <int N, int... Ns>
    struct tag {};

    template <int N, int... Ns>
    void addLayer(tag<N, Ns...>) {
        layers.push_back(N);
        addLayer(tag<Ns...>());
    }

    template <int N>
    void addLayer(tag<N>) {
        layers.push_back(N);
    }

public:
    network() {
        layers.reserve(sizeof ... (neurons));
        addLayer(tag<neurons...>());
    }
};

int main()
{
  network<1,2,3,4,5> n;
  for(int i : n.layers)
      std::cout << i;
  std::cout << '\n';
  return 0;
}

注意:这里的计数是由传递给模板的整数数量决定的。

【讨论】:

    猜你喜欢
    • 2011-11-15
    • 2014-10-20
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多