模板和函数指针
Template and function pointer
是否可以从模板中存储类,而不将整个类作为模板?
任务:
我有两个函数,v1没有参数,v2有参数,如果v1在某个地方被调用,则Use[(]不会发生任何变化,如果v2在某个位置被调用,Use[()]应该使用我从DoSometh(T*)获得的实例执行一个函数_ptr。
例如
class MyClass
{
//v1 no parameters
void DoSomething()
{
}
//v2 with parameter
template<class T>
void DoSomething(T* instance, void (T::*func)())
{
store somewhere?? = instance;
}
void Use()
{
//if DoSometh(T* instance) was used before
if(instance != NULL)
{
(*instance->)//call function pointer from DoSomething(T*,void (T::*)())
}
}
}
std::function problem
update:
class Timer : public ITickable
{
std::function<void()> test; //adding this does weird things
virtual void Tick() {}
}
class MyClass
{
ITickable* tickable_;
void Tick()
{
tickable_->Tick(); //let's assume it points to a Timer obj.
}
}
我认为std::function
和std::bind
(C++11)确实实现了您想要的,正如评论中所建议的那样。Timer类的简化模型可以是:
class Timer
{
std::function<void()> m_task;
public:
template <typename T>
void setTask(T &instance, void (T::*fcn)()) // consider T const & if applicable
{
m_task = std::bind(fcn, &instance);
}
void fire()
{
if (m_task) // std::function overloads operator bool()
m_task();
}
};
当用一个对象和一个可以在该对象上调用的成员函数调用setTask
时,就会创建一个std::function
对象(当然,您可以选择在构造函数中执行此操作)。当计时器触发时,会检查此对象(使用std::function
提供的operator bool()
),如果它是可调用的(例如,当setTask()
以前被调用时),它会调用函数。
例如:
class MyClass
{
public:
void func()
{
std::cout << "Hi from MyClassn";
}
};
class MyOtherClass
{
public:
void func()
{
std::cout << "Hi from MyOtherClassn";
}
};
int main(int argc, char **argv)
{
MyClass x1;
MyOtherClass x2;
Timer t1, t2;
t1.setTask(x1, &MyClass::func);
t2.setTask(x2, &MyOtherClass::func);
t1.fire();
t2.fire();
}
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址