在映射中存储模板类函数指针
Store template class function pointers in map
>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
};
}
我认为IsPresent
和IsEnabled
是一个错字。
编辑:针对成员指针进行了更新。
这里的问题是不可能有一个指向"任何"类类型的指针,因此您必须将其定义为模板,并为每个派生类使用单独的模板。
如果您需要存储指向单个数据结构的所有指针,则可以使用std::function
和 lambda 来解决这个问题。
相关文章:
- 带有类的函数指针
- 通过函数指针定义类范围之外的方法
- 从类成员函数到类 C 函数指针的转换
- 返回类函数指针 c++
- 在映射中存储模板类函数指针
- 模板类函数指针类型别名
- C++ - 基类函数指针调用的替代方法
- 是否可以使用包含{sub,super}类函数指针的回调表
- 通过基类函数指针调用派生类
- 类函数指针作为参数
- C++中抽象成员和类函数指针的深层复制构造函数
- 将类函数指针传递到另一个类
- 通过 VC++ 中的类 A 函数指针调用类成员函数(类 B)
- 没有为c++类函数指针注册python类
- 如何在另一个类或结构中使用类函数指针
- 如何:类函数指针(c++)
- 使用基类函数指针访问派生类成员函数
- 调用与父类函数指针同名的函数
- boost绑定类函数指针
- 如何从另一个类的函数中获取非静态函数的类函数指针?