模板别名未被识别为有效



我遇到以下问题:

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;}
}

哪一个看起来是一样的?

这里S是模板参数的名称:

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

作为类比,考虑

void foo(int x) {};
foo(x);

调用不会编译,因为参数的名称在很大程度上与传递参数无关。如果要实例化matS,则需要指定S应该是什么,或者将setData本身作为模板。为了清楚起见,我为setData的论点选择了一个不同的名字:

template<class S> using matS = std::vector<std::vector<S>>;
template<class T>  //; <--- no ; here !
void setData(matS<T> dat) {
if (isHorizontallyPacked()) {m_rows = dat;}
else {m_cols = dat;}
}

或某些混凝土类型,例如int:

// vv this is not a template now
void setData(matS<int> dat) {
if (isHorizontallyPacked()) {m_rows = dat;}
else {m_cols = dat;}
}

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

#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;}
}

最新更新