我遇到了以下问题:
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 scope
和 error: 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;}
}
看起来它们是一样的?
答案 0 :(得分:1)
您必须为 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;}
}
答案 1 :(得分:1)
这里的 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;}
}