【问题标题】:Passing a constexpr array from non-type parameter pack as template argument fails将非类型参数包中的 constexpr 数组作为模板参数传递失败
【发布时间】:2017-09-08 08:31:30
【问题描述】:

我将参数包中的一个数组定义为 constexpr。然后我想将此数组作为模板参数传递给另一个模板。但是,我收到外部链接错误。这里有什么问题?我认为 constexpr 可以很容易地作为模板参数转发。

// Example program
#include <array>
#include <iostream>
#include <string>


template <size_t X>
using iMat1D = std::array<size_t, X>;

template <size_t SizeOfDims, const iMat1D<SizeOfDims> &DIMs>
struct test{
  static void run() {
  }
};

template <std::size_t... DIMS> 
struct solver_walker {
  static void run() {
    constexpr std::size_t N = sizeof...(DIMS);
    constexpr std::array<size_t, N> dims = {{DIMS...}};
    test<N, dims>::run();
  };
};

int main()
{
    solver_walker<1,2,3,4>::run();
}

【问题讨论】:

    标签: templates c++14 variadic-templates


    【解决方案1】:

    您正在尝试将 reference 作为模板参数传递给dims。由于dims 不是static 变量,因此该引用不是常量表达式

    您可以通过将dims 设为static 变量来解决此问题:

    template <std::size_t... DIMS> 
    struct solver_walker {
      static void run() {
        constexpr std::size_t N = sizeof...(DIMS);
        static constexpr std::array<size_t, N> dims = {{DIMS...}};
        test<N, dims>::run();
      };
    };
    

    live example on wandbox

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 2017-09-17
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多