gpt4 book ai didi

c++ - 在类构造函数中,定义一个 T 类型的 vector

转载 作者:行者123 更新时间:2023-11-27 23:41:58 26 4
gpt4 key购买 nike

我已经可以在 public: header 中定义一个具有固定参数类型的函数指针 vector ,然后在构造函数中更新它。但是,如果我希望能够传递带有任何类型参数的函数指针 vector ,我该如何在构造函数更新它之前定义它?

#include <iostream>
#include <vector>

class foo {
public:
std::vector<void (*)(int)> functions;

foo(std::vector<void (*)(int)> x) {
functions=x;
}

void run() {
functions[0](2);
}
};

void square(int n) { std::cout << n*n; }

int main() {
foo* bar=new foo(std::vector<void (*)(int)>{square});
bar->run();
return 0;
}

现在,我如何将 vector 传递给任何类型的构造函数?

//snippet from above
std::vector<void (*)()> functions; //what do i do here?

template <typename T>
foo(std::vector<void (*)(T)> x) { //this works fine
functions=x;
}

最佳答案

您可以将类改为类模板

template<class T>
class foo {
public:
std::vector<void (*)(T)> functions;
foo(std::vector<void (*)(T)> x) : functions(x)
{ }
...
}

foo<int>* bar=new foo(std::vector<void (*)(int)>{square});

我还建议从函数指针切换到 std::function并且您不使用原始指针。使用 std::unique_ptr或其表亲之一。

关于c++ - 在类构造函数中,定义一个 T 类型的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54016321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com