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

Store template class function pointers in map

本文关键字:类函数 指针 存储 映射      更新时间:2023-10-16

>Template class

template <class F>
class MyClass
{
public:
inline static bool isPresent()
{
if (F::getDetails())
{
return F::isPresent();
}
return false;
};
};

基类

class Base
{
public:
inline static bool isPresent()
{
...
}
static bool getDetails();
};

派生类

class Derived : public Base
{
public:
};

模板类函数调用

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

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

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是一个错字。

编辑:针对成员指针进行了更新。

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

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