首页 > 解决方案 > 模板别名未被识别为有效

问题描述

我有以下问题:

  template<class S>
  void setAtIdx(int idx, std::vector<S> toSet) {
      cdVec container = cdVec(toSet.size);
      std::transform(toSet.begin(), toSet.end(), container,
                     [](S el) -> std::complex<double>{return std::complex<double>(el);});
      if (isHorizontallyPacked()) { m_rows[idx] = container; }
      else { m_cols[idx] = container; }
  };

  template<class S> using matS = std::vector<std::vector<S>>;
  void setData(matS<S> dat) {
      // same issue pops up when I do setData(matS dat)

      if (isHorizontallyPacked()) {m_rows = dat;}
      else {m_cols = dat;}
  }

我的编译器给我带来了问题,setData并且正在吐出error: ‘S’ was not declared in this scopeerror: template argument 1 is invalid.

当我这样做时问题就消失了

  template<class S> ;
  void setData(std::vector<std::vector<S>> dat) {
      // same issue pops up when I do setData(matS dat)

      if (isHorizontallyPacked()) {m_rows = dat;}
      else {m_cols = dat;}
  }

看起来它们会是一样的吗?

标签: c++templates

解决方案


您必须为 using 和函数指定模板:

#include <vector>
  
template<class S>
void setAtIdx(int idx, std::vector<S> toSet) {
    cdVec container = cdVec(toSet.size);
    std::transform(toSet.begin(), toSet.end(), container,
                    [](S el) -> std::complex<double>{return std::complex<double>(el);});
    if (isHorizontallyPacked()) { m_rows[idx] = container; }
    else { m_cols[idx] = container; }
};

template<class S> 
using matS = std::vector<std::vector<S>>;

template<class S>
void setData(matS<S> dat) {
    // same issue pops up when I do setData(matS dat)

    if (isHorizontallyPacked()) {m_rows = dat;}
    else {m_cols = dat;}
}

推荐阅读