我试图使用一个以结构为参数的函数。
xmlns:th="http://www.thymeleaf.org"
在一个例子中(工作正常),结构定义了一个固定大小的列表/向量(我不知道哪一个是正确的)。
/**
* @param chunk A vector of C-style structs to hold the samples.
* @param timestamps A vector to hold the time stamps.
* @return True if some data was obtained.
*/
template<class T> bool the_function(std::vector<T> &C, std::vector<double> ×t){
T sample;
C.clear();
timest.clear();
while (double ts=other_function(sample,0.0)) {
C.push_back(sample);
timest.push_back(ts);
}
return !chunk.empty();
}
但我想使用与我可以选择的列表大小 n 相同的功能。
我尝试在结构中添加一个参数,以便我选择尺寸:
using namespace std
struct sample {
float d[64];
};
int main(int argc, char* argv[]) {
// Some stuff is made
vector<sample> result;
vector<double> ts;
if (double timest = the_function(result, ts)){
cout << timest << endl;
}
return 0;
}
要使用它,我在例子中使用它:
template <int T>
struct channels {
float d[T];
};
但是我在声明结果的行上得到了错误:
错误:&#39; n&#39;的值不能用于常量表达式
我尝试使用
const int n = function_count();
// function_count is a function from a class that return an int
vector<channels<n> > result;
vector<double> ts;
并且它有效,所以我认为function_count有所不同,但是function_count只返回一个int。
那么我必须使用另一种 struct 吗?如何创建可以与函数定义的参数一起使用的结构?
修改
我想在不修改const int n = 64;
和function_count
的情况下找到解决方案,因为我没有做出这两个功能。
我尝试仅使用向量来声明the_function
,编译有效,但是当它尝试使用它时,我收到了错误:result
答案 0 :(得分:3)
std::vector
的大小可自动调整,即其大小可根据需要增加或减少。所以只需创建一个合适类型的向量。
void push_back (const value_type& val);
std::vector
void pop_back();
std::vector
您还可以创建初始大小设置的矢量。例如,以下内容将向量vec
的大小设置为5:
std::vector<float> vec(5);
答案 1 :(得分:0)
const
和constexpr
不同。
模板参数需要常量表达式,因此您应该将代码修改为:
constexpr int function_count() { return 64; }
void foo()
{
// ...
constexpr int n = function_count();
std::vector<channels<n> > result;
// ...
}
如果function_count
不能constexpr
,则必须将struct channels
更改为动态,例如:
struct channels {
std::vector<float> d;
};