【问题标题】:In a class constructor, define a vector of T type在类构造函数中,定义一个 T 类型的向量
【发布时间】:2019-05-29 16:34:05
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c++ c++11 templates vector


    【解决方案1】:

    您可以将类改为类模板

    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 或其表亲之一。

    【讨论】:

    • 啊,谢谢,现在可以使用了。将考虑进行其他更改。
    • 请注意,通过将&lt;class T&gt; 更改为&lt;class... T&gt;,您可以轻松拥有任意数量的参数foo
    猜你喜欢
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 2014-10-12
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多