c++ - 返回一个 void* 数组

标签 c++ arrays function-pointers void-pointers

我正在构建一个 C++ 程序,需要存储字符串到函数指针的映射。但是,每个函数可能有不同的返回类型和参数。我试图解决这个问题的方法是创建函数,接受一个 void 指针数组并返回一个 void 指针数组,然后根据需要转换参数和返回值。

为了弄清楚这是如何工作的,我正在尝试构建一个简单的虚拟对象,但无法编译它。我尝试了很多方法,但不断收到不同的错误。这是一个例子:

#include <string>
#include <iostream>
#include <map>

using namespace std;

void** string2map(void** args){
    //takes a string of the form "key:value;key:value;..." and returns a map<string,string>
    string st = *((string**) args)[0];
    map<string, string> result = map <string, string>();
    //code doesnt matter
    return (void*) &((void*) &result);
}

int main(){
    string test = "hello:there;how:are you?";
    map<string, string> result = *(map<string, string>**)string2map((void*) &((void*) &test))[0];

    return 0;
}

当我尝试编译时,我得到:

void.cpp: In function 'void** string2map(void**)':
void.cpp:12:34: error: lvalue required as unary '&' operand
void.cpp: In function 'int main()':
void.cpp:17:89: error: lvalue required as unary '&' operand

显然这里有很多问题,但我真的不知道从哪里开始。谁能告诉我上面的代码有什么问题,或者给我一个替代方法来代替我目前的做法?

注意

我返回 void** 而不仅仅是 void* 的原因是,在某些情况下,我可能需要返回多个不同类型的值。一个例子是,在上面,我想返回结果映射和映射中的条目数。不过,我什至还没有弄清楚如何构建该数组。

编辑

因此,根据迄今为止的答复,很明显这是解决此问题的错误方法。考虑到这一点,有人能提出更好的建议吗?我需要能够将各种函数存储在单个映射中,这意味着我需要能够为采用和返回不同类型的函数定义单个数据类型。能够返回多个值非常重要。

最佳答案

您正在转换 map<string,string>void** ,返回它然后将其转换回 map<string,string 。为什么不直接返回 map<string,string> ?它也称为string2map这意味着您只能使用字符串来调用它(由您传入一个字符串的事实支持,该字符串被转换为 void** 然后直接转换回来)。除非您有充分的理由在 void** 之间进行转换到处都是,这可能就是您所需要的:

#include <string>
#include <iostream>
#include <map>

using namespace std;

map<string, string> string2map(string st){
    map<string, string> result = map <string, string>();
    //code doesnt matter
    return result;
}

int main(){
    string test = "hello:there;how:are you?";
    map<string, string> result = string2map(test);
    return 0;
}

编辑:

我刚刚重读了你的问题。您可能想要查找广义仿函数并查看 Boost 的 std::function尽可能解决这个问题。可以通过包装类更改函数的返回类型,例如:

template< class T >
class ReturnVoid
{
public:
    ReturnVoid( T (*functor)() ) : m_functor( functor ) {}

    void operator() { Result = functor(); }

private:
    T (*m_functor)();
    T Result;
};

//  Specialise for void since you can't have a member of type 'void'
template<>
ReturnVoid< void >
{
public:
    ReturnVoid( T (*functor)() ) : m_functor( functor ) {}

    void operator() { functor(); }

private:
    T (*m_functor)();
};

使用它作为包装器可能会帮助您在同一数组中存储具有不同返回类型的仿函数。

关于c++ - 返回一个 void* 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13803720/

相关文章:

c++ - 如何在没有临时变量的情况下传递指向整数的指针?

C# 比较 4 个字符串数组

python : can I get a memoryview or a bytearray mapping to a mmap

c++ - 将可变参数函数的参数封装在类实例中

fortran - fortran中的过程指针

c++ - 无法从对象访问函数

C++检查字符串中是否只存在以下字符

c++ - 我如何在 C++11 中解决 SICP 2.4

java - 在 JSON 数组中查找 JSON 对象

delphi - 具有不同签名的函数指针(例如 : optional parameter with a default value)