2015-06-23 155 views
0

是否有可能从模板中存储类而不使整个类成为模板?模板和函数指针

任务:

我有两个功能,V1无参数和参数V2, 如果V1被称为地方什么也没有发生与使用(),如果V2被称为地方使用()应执行function_ptr与我从DoSometh(T *)获得的实例。

例如

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. 
} 


} 
+1

你*有*使用函数指针?你不能使用标准库用于所有可调用函数的模板吗?然后,您可以传递一个'std :: function'对象,泛型函数对象,'std :: bind'对象,普通(或静态成员)函数指针和lambda表达式,而不用担心实例或存储信息。 –

+0

'void *'或者甚至更好 - 'ParentInterface *' – Amartel

+3

显示一个真实的用例示例。看起来好像可能有更好的解决方案。 –

回答

1

我觉得std::functionstd::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对象(你可以选择做这当然在构造函数中)。当定时器触发时,将检查该对象(使用operator bool(),由std::function提供),并且如果它是可调用的(例如,之前调用过setTask()),它将调用该函数。

例如:

class MyClass 
{ 
public: 
    void func() 
    { 
     std::cout << "Hi from MyClass\n"; 
    } 
}; 

class MyOtherClass 
{ 
public: 
    void func() 
    { 
     std::cout << "Hi from MyOtherClass\n"; 
    } 
}; 


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(); 
} 
+0

hmm,不知何故,当我写std :: function m_task;在我的类定义中,没有任何工作了 – jeromintus

+0

继承和std :: function有问题吗? – jeromintus

+0

如果例如,计时器有一个基类ITickable? 'class Timer:public ITickable {}' 可能会导致问题吗? – jeromintus