具有不同签名的函数数组

时间:2011-09-07 08:51:18

标签: c++ function-pointers c++11 method-signature

我有这个课程:

class Foo
{
    ...
};

class Foo1 : public Foo
{
    ...
};

...

class FooN : public Foo
{
    ...
};

是否可以使用这类签名的函数数组:

void f1(Foo1*){}
...
void fN(FooN*){}

如果这些函数是非静态成员函数而不是常规函数,是否有任何变化?我不认为这会改变一些事情。

谢谢!

10 个答案:

答案 0 :(得分:3)

编辑替代的非基于虚拟功能的解决方案here

void(*)(Foo*)类型无法转换为void(*)(Bar*)类型且有充分理由。

您应该使所有功能都采用Interface*参数,并且所有FooN都应来自Interface

struct Interface {
    virtual ~ Interface () {}
    // ...
};

struct Foo1 : public Interface {
    // ...
};

struct Foo2 : public Interface {
    // ...
};

void f1 (Interface *);
void f2 (Interface *);

void (*functions)(Interface*) [] = {f1, f2};

functions[0] (new Foo1 ());
functions[0] (new Foo2 ());
functions[1] (new Foo1 ());
functions[1] (new Foo2 ());

f1f2的实现可以在运行时检查其参数是否是使用dynamic_cast并检查nullptr的特定实现。在编译时检查的唯一方法是使f1f2采用特定类型,将它们放入匿名数组中,但显式调用它们。


回答你问题的第二部分 - 是的,如果它们是非静态成员函数,那就重要了,因为the size of the pointer is not constant

答案 1 :(得分:2)

您可以使用功能对象。请参阅下面的示例,了解如何执行此操作。如果你喜欢这个想法,你应该看看boost.signal / boost.bind和c ++ 0x对应物。

class Foo1 {};
class Foo2 {};
class Foo3 {};

void func1(Foo1*) {}
void func2(Foo2*) {}
void func3(Foo3*) {}

class FuncObjBase {
public:
    virtual void operator()() = 0;
};

template <class T>
class FuncObj : public FuncObjBase {
public:
    typedef void (*Funcptr)(T*);
    FuncObj(T* instance, Funcptr funcptr) : m_Instance(instance), m_Func(funcptr) {}
    virtual void operator()() { m_Func(m_Instance); }
private:
   T* m_Instance;
   Funcptr m_Func;
};

int main(int argc, char *argv[])
{
    Foo1 foo1;
    Foo2 foo2;
    Foo3 foo3;
    FuncObjBase* functions[3];
    functions[0] = new FuncObj<Foo1>(&foo1, func1);
    functions[1] = new FuncObj<Foo2>(&foo2, func2);
    functions[2] = new FuncObj<Foo3>(&foo3, func3);
    for(unsigned int i = 0; i < 3; i++) {
        (*functions[i])();
    }
    return 0;
}

答案 2 :(得分:1)

C ++是一种静态类型语言,包括函数类型。在每行代码中,C ++编译器必须能够确定函数签名是否有效以及要调用的函数(或指针)。

为了做你正在谈论的事情,你需要能够在运行时基于在运行时放入数组的值来恢复指针的类型。并且多态性是您在运行时可以获得的唯一与类型相关的事物。甚至 只处理类的类型。究竟要调用哪个函数不值得辩论。

你可以做的最好的事情就是使用类似boost::variant的数组。您可以在变体中存储一组特定的函数原型,可能使用boost::function。但是,它只是一个有界集,而不是任意函数类型。调用它们会相当困难,因为您首先必须验证变量确实是预期的函数类型,然后调用它。

另一种方法是使用boost::any数组。除此之外,类型可以是任何函数类型。再次,调用它将需要将其转换为预期的函数类型之一。问题是复杂的,因为函数类型可以实际上是任何。因此,如果它不是预期的函数类型之一,则必须提供后备。

如果函数列表很小并且确定了编译时间,则可以使用boost::tuple作为临时“数组”。但是,您必须使用模板元编程来迭代它们。当然,如果是这种情况,您可以使用包含相应类型的函数指针的结构。

答案 3 :(得分:1)

您可以使用Variadic模板在C ++ 11中执行此操作。检查我的答案,该答案与您想要的相似,但地图位于:https://stackoverflow.com/a/33837343/1496826

答案 4 :(得分:0)

您可以使用功能对象。

例如Boost.Signal或来自C ++ 0x / TR1

的那些

答案 5 :(得分:0)

您可以创建其特定参数类的f1fN个成员的函数,将它们命名为相同并使用虚拟调度来调用正确的函数。然后你只需要将成员函数的指针填充到数组中。

答案 6 :(得分:0)

你想要的是covariant argument types。这在C ++中不受支持,因为它打破了类型安全性。为了更好地理解这一点,我们举一个简单的例子:

struct Vehicle {};
struct Tricycle : Vehicle {};
struct Tank : Vehicle {};

void drive(Vehicle const & b) { ... }
void giveToChild(Tricycle const & b) { ... }

这里我们有一个简单的类型层次结构,以及两个分别引用基类和一个派生类的函数。现在,如果您要求的是允许的,我们可以执行以下操作:

typedef void (*funcPtr)(Vehicle const &);

funcPtr = &giveToChild; // this is not allowed
funcPtr(Tank());        // oops, I just gave a tank to my child!

该语言可以实现某种运行时类型验证,但这不是C ++的工作方式。

然而,可以允许反向转换(逆变)而没有任何问题(实际上,C#代理允许它),但由于某些我不知道的原因在C ++中是不可能的。以下是它允许的样本:

typedef void (*funcPtr)(Tricycle const &);

funcPtr = &drive;    // this could be allowed, but is not (in C++)
funcPtr(Tricycle()); // I can only drive a tricycle, but that's ok since it's a
                     // vehicle and I know how to drive all vehicles

所以基本上,如果没有在调用原始函数之前使用会检查参数类型的转发函数,那么你想要实现的是不可能的:

void forwardFN(Foo * f)
{
    FooN * instance = dynamic_cast<FooN *>(f);

    if (instance) fN(instance);
    else throw type_exception();
}

答案 7 :(得分:0)

我找到了解决此问题的方法:

#include <iostream>
#include <vector>

class Foo
{
};

class Foo1 : public Foo
{
};

class Foo2 : public Foo
{
};

class Foo3 : public Foo
{
};


void f1(Foo1*)
{
    std::cout<<"f1\n";
}

void f2(Foo2*)
{
    std::cout<<"f2\n";
}

void f3(Foo3*)
{
    std::cout<<"f3\n";
}

template<typename T>
void AddPointer(std::vector<typename void (*)(Foo*)>& fPointers, T function)
{
    fPointers.push_back(reinterpret_cast<void (*)(Foo*)>(function));
}

void main()
{
    std::vector<typename void (*)(Foo*)> fPointers;

    AddPointer(fPointers, f1);
    AddPointer(fPointers, f2);
    AddPointer(fPointers, f3);

    Foo1 foo1;
    Foo2 foo2;
    Foo3 foo3;

    fPointers[0](&foo1);
    fPointers[1](&foo2);
    fPointers[2](&foo3);
}

答案 8 :(得分:0)

我建议使用std::tuple代替std::array或C数组。使用std::tuple可以存储不同类型的元素。

答案 9 :(得分:0)

这是一种类型安全的通用方法,可以强制客户端代码正确。

class Manager {
public:

    typedef int /* or whatever */ ID;

    template <typename Function>
    static void save (Function * f, ID id) {
        functions <Function> () .add (id, f);
    }

    template <typename Function>
    static Function * get (ID id) {
        return functions <Function> () .get (id);
    }

private:

    template <typename Function>
    class FunctionStore {
    public:

         void add (Function *, ID);
         Function * get (ID);

    private:
         // or vector, if you know ID is int.
         std :: map <ID, Function *> m_functions;
    };

    // type_index is C++11 but you can implement it in C++03.
    // void* here is unpleasant but you can improve it, RAII it.
    typedef std :: map <std :: type_index, void *> Store;
    static Store m_store;

    template <typename Function>
    FunctionStore <Function> & functions () {
        FunctionStore <Function> * fs;

        Store :: iterator i = m_store .find (typeid Function);

        if (m_store .end () == i) {
            fs = new FunctionStore <Function> ();
            m_store [typeid Function] = fs;
        }
        else {
            // This void* cast is OK because it's internally controlled
            // and provably correct.
            // We don't have to trust the library to not abuse it.
            fs = static_cast <FunctionStore<Function>*> (i -> second);
        }

        return *fs;
    }
};

// In the library

void foo1 (Foo *);
void bar1 (Bar *);
void foo2 (Foo *);
void bar2 (Bar *);

void init () {
    Manager :: save (foo1, 1);
    Manager :: save (foo2, 2);
    Manager :: save (bar1, 1);
    Manager :: save (bar2, 2);

    Manager :: get <void(Foo*)> (1) (new Foo ()); // OK, calls foo1
    Manager :: get <void(Foo*)> (1) (new Bar ()); // Will not compile
    Manager :: get <void(Bar*)> (2) (new Bar ()); // OK, calls bar2
}

如果您不希望m_store中的查询开销(和/或想要避开void中的Manager::Store),您可以将Manager本身设为模板类,缺点是你现在必须注意你的静态m_store定义。如果您知道客户端将只使用一组Function个签名,那就没问题。

void init () {
    Manager <void(Foo*)> :: save (foo1, 1);
    Manager <void(Foo*)> :: save (foo2, 2);
    Manager <void(Foo*)> :: save (bar1, 1); // Won't compile
    Manager <void(Bar*)> :: save (bar1, 1);
    Manager <void(Bar*)> :: save (bar2, 2);

    Manager <void(Foo*)> :: get (1) (new Foo ()); // OK, calls foo1
    Manager <void(Foo*)> :: get (1) (new Bar ()); // Will not compile
    Manager <void(Bar*)> :: get (2) (new Bar ()); // OK, calls bar2
}

init函数说明了我在其他帖子的评论中提出的关键点:如果你知道你要调用哪个类型的函数那么你 know 要获取的函数集合。没有需要尝试将它们全部塞进来,这只会损害您的类型安全性。