在映射中存储模板 class 函数指针

Store template class function pointers in map

模板class

template <class F>
class MyClass
{
public:

inline static bool isPresent()
{
    if (F::getDetails())
    {
        return F::isPresent();
    }

    return false;
};
};

基础class

class Base
{
public:

inline static bool isPresent()
{
    ...
}

static bool getDetails();
};

派生class

class Derived : public Base
{
public:

};

模板class函数调用

const bool isEnabled = MyClass<Derived>::isPresent();

我想将上述函数调用存储为映射中的指针。但是,模板参数可以是不同的派生 classes。我该怎么做?

using MyClassPtr = bool (MyClass<Base>::*)();
map<string,MyClassPtr>  data;
data = {  
    {"abc", &MyClass<Derived>::isPresent},
    {"wer", &MyClass<Derived1>::isPresent}
};  

我收到以下错误:

error: no match for ‘operator=’ (operand types are ‘std::map<std::basic_string<char>, bool (App::MyClass<App::Derived>::*)()>’ and ‘<brace-enclosed initializer list>’)
 data = {

由于您的成员函数是静态的,因此您必须将函数指针定义为普通指针类型:

using MyClassPtr = bool (*)();

缩减的完整代码为我编译:

class Base
{
    public:
        static bool isEnabled() { return true;}
};

class Derived: public Base { };
class Derived1: public Base { };

template <class F>
class MyClass
{
    public:
        inline static bool isEnabled()
        {
            return F::isEnabled();
        }

        bool AnyMember() { return true; }
};

template <typename T>
using MyMemberPtr = bool (MyClass<T>::*)();
using MyClassPtr = bool (*)();



int main()
{
    std::map<string,MyClassPtr>  data;
    data = {
        {"abc", &MyClass<Derived>::isEnabled},
        {"wer", &MyClass<Derived1>::isEnabled}
    };

    std::map<string, MyMemberPtr<Derived>> dataMember;

    dataMember = {
        {"xyz", &MyClass<Derived>::AnyMember}
    };

    std::map< string, std::function< bool() > > anyFuncs;

    anyFuncs =
    {
        { "one", [](){ return MyClass<Derived>::isEnabled();} },  // going to static
        { "two", [](){ return MyClass<Derived>().AnyMember(); } }, // going to member for Derived
        { "three", [](){ return MyClass<Derived1>().AnyMember(); } } // going to member for Derived1
    };
}

我认为 IsPresentIsEnabled 是错字。

编辑:更新成员指针。

这里的问题是不可能有指向 "any" class 类型的指针,因此您必须将其定义为模板并用于每个派生的 class一个单独的。

如果您需要存储指向单个数据结构的所有指针,您可以使用 std::function 和 lambda 来解决该问题。