Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++将指针的参数更改为数组参数_C++_Arrays_Function Pointers_Type Mismatch_Function Binding - Fatal编程技术网

C++将指针的参数更改为数组参数

C++将指针的参数更改为数组参数,c++,arrays,function-pointers,type-mismatch,function-binding,C++,Arrays,Function Pointers,Type Mismatch,Function Binding,我有一个带有数组的类,其大小在构造函数中指定。该类还存储指向函数的指针,该函数将指针作为参数,调用该参数时,该指针将被设置为指向数组。我还有一个bind函数,它将函数指针设置为与作为参数传入的其他函数相等。这允许我绑定任意函数,这些函数的参数将包含数组。看起来是这样的: template <typename T> class MyClass{ public: MyClass(int s) : size(s) { arr = new T[size]; } MyClass

我有一个带有数组的类,其大小在构造函数中指定。该类还存储指向函数的指针,该函数将指针作为参数,调用该参数时,该指针将被设置为指向数组。我还有一个bind函数,它将函数指针设置为与作为参数传入的其他函数相等。这允许我绑定任意函数,这些函数的参数将包含数组。看起来是这样的:

template <typename T>
class MyClass{
public:
    MyClass(int s) : size(s) { arr = new T[size]; }
    MyClass() { delete[] arr; }

    virtual inline void bindFunc(void(*func)(T[])) { fn = func; } //types match, ok
    inline void callFunc(){fn(arr);} 
        /*Yes, I know I need a size parameter to correctly
        iterate over arr, I took out this info to help make things more clear, just pretend 
        arr is null terminated and the bound fn function knows how to correctly handle it*/

private:

    const int size; 
    T arr[];
    void(*fn)(T[]);
};
class derived: public MyClass<double> {
public:
    derived() : MyClass(2) {}

    inline void bindFunc(void(*func)(double, double)) { fn = func; } //error, type mismatch, obviously
};
我不确定我想要的是否可能,但我有兴趣了解更多关于它的知识或更正确的设计模式。我试过摆弄函数,但我自己什么都想不出来。感觉语言中会有一个特性使类似的事情成为可能,这就是为什么我想首先输入这个问题

大部分我在C++中的实验是为了学习,我知道我的方法可能对我正在完成的事情有点疯狂,但希望它能成为一个更好的程序员。提前感谢您的洞察力

如果使用std::function而不是原始函数指针,则可以使用lambda以任何方式转换参数:

template <typename T>
class MyClass{
    std::function<void(T[])>  fn;
public:

virtual inline void bindFunc(void(*func)(T[])) { fn = func; } //types match, ok
virtual inline void bindFunc(void(*func)(T, T)) {
    fn = [func](T args[]) { func(args[0], args[1]); }; }

为了获得更大的灵活性,还可以将func参数设置为std::函数

为什么要使用原始数组和手动新删除。这有什么必要?std::vector作为一个类成员,乍一看应该很合适。我本来可以简化事情并使用向量,但实际上没有什么区别,我认为使用数组会更容易显示问题,而使用向量时问题肯定仍然存在。这似乎完全符合我的要求,非常感谢!但我对std::functional了解不多,在VS2017中我的行为变得非常怪异。如果我将std::functionvoidT[]fn;除了variableStateHandle类之外的任何地方,它下面都会出现一个红色的曲线,表示缺少类模板std::函数的参数列表。fn在我的代码中的mousePos类中也不可见,即使它应该是可见的。知道会发生什么吗?再次感谢!是的,我刚刚想好了,正要评论哈!很好,谢谢!
template <typename T>
class MyClass{
    std::function<void(T[])>  fn;
public:

virtual inline void bindFunc(void(*func)(T[])) { fn = func; } //types match, ok
virtual inline void bindFunc(void(*func)(T, T)) {
    fn = [func](T args[]) { func(args[0], args[1]); }; }