繁体   English   中英

c ++ void * to函数的参数

[英]c++ void* to parameter to a function

我在某个库中有这个功能:

class myConsole
{
    void addCommand( std::string command, void* fn );
    ...
}

在我班上我有这个功能:

void myApp::TestFn( const std::vector<std::string> & args )
{
    // do something
}

在同一个班级我称之为:

void myApp::initApp( )
{
    myConsole::getSingleton( ).addCommand( "FirstTest", &myApp::TestFn );
}

但这给了我这个错误:

错误c2664无法将参数2从'void(__ thiscall myApp :: *)(const std :: vector <_Ty>&)'转换为'void *'

我该怎么解决这个问题?

提前致谢!

无法解决这个问题。 您无法可靠地将函数指针强制转换为void *和back。

(我建议你重新设计程序并保持void* ;在C ++中并不需要它。)

这里的问题是你试图传递一个类方法,因为它是一个void *指针。 这是不可能做到的。

正确的方法是使用void addCommand (std::string, void *)方法的模板。 就像是

class myConsole {
    template <typename T>
    void addCommand( std::string command, T f);
};

struct Callback {
    myApp &app;
    Callback (myApp &a) : app(a) {
    }
    void operator() (const std::vector<std::string> &args) {
        app.TestFn(args);
    }
};

void myApp::initApp( )
{
    myConsole::getSingleton( ).addCommand( "FirstTest", Callback(*this) );
}

这为您提供了C ++中的回调原则,但我认为您需要比此解决方案更灵活的东西,因为您实际上想要自动选择将由回调执行的命令(在本例中为TestFn )。

你应该避免使用void* ,尤其是在尝试使用函数指针时。 我将假设你只关注myApp类中的成员函数指针,并且你只对const std::vector<std::string> &args作为参数的成员函数指针感兴趣。 此typedef将创建适当的类型并将其MemFunType

typedef void (myApp :: * MemFunType) (const std::vector<std::string> &);

这是一个完整的示例(在ideone上 ),其中有两个您可能感兴趣的成员函数, TestFnTestFnBackwards 这个例子可能不是很有用,但它提供了一些成员函数指针的例子。

#include<iostream>
#include<vector>
using namespace std;

struct myApp;

struct myConsole
{
        typedef void (myApp :: * MemFunType) (const std::vector<std::string> &);
            void addCommand( std::string command, MemFunType fn );
};

struct myApp {
        void TestFn( const std::vector<std::string> & args ) {
                cout << " TestFn" << endl;
                for(std :: vector<std::string> :: const_iterator i = args.begin(); i!=args.end(); i++) {
                        cout << *i << endl;
                }
        }
        void TestFnBackwards( const std::vector<std::string> & args ) {
                cout << " TestFnBackwards" << endl;
                for(std :: vector<std::string> :: const_reverse_iterator i = args.rbegin(); i!=args.rend(); i++) {
                        cout << *i << endl;
                }
        }
        static myApp & getSingleton();
} ma;
myApp& myApp :: getSingleton() {
        return ma;
}

void myConsole :: addCommand( std::string , MemFunType fn ) {
        vector<string> words;
        words.push_back("hello");
        words.push_back("world");
        myApp &ma = myApp :: getSingleton();
        (ma.*fn)(words); // execute the member on the singleton object, using the words as the argument.
}

int main() {
        myConsole m;
        m.addCommand( "FirstTest", &myApp::TestFn );
        m.addCommand( "FirstTest", &myApp::TestFnBackwards );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM