简体   繁体   English

模板函数内的函数指针

[英]Function pointer inside template function

Hello Im begginer with c++ and Im stuck with this problem.你好,我是 C++ 的初学者,我一直在解决这个问题。 I have template class as you can see bellow and there is another template method PrintSpecificObject.我有模板类,如下所示,还有另一个模板方法 PrintSpecificObject。 In real project I have a collection of differents objects and I need for example print just object which could be cast do "K".在实际项目中,我有一组不同的对象,例如,我只需要打印可以转换为“K”的对象。 Anyway, my problem is with "PrintThatObject" method or with that how i call it in main.无论如何,我的问题是“PrintThatObject”方法或我在main中如何调用它。 Thanks for help.感谢帮助。

     template<typename T>
        class Foo {
        public:
            std::vector<T*> v;

            template<typename K>
            void PrintSpecificObject(void(*uFunc)(K*)) {
                for (std::vector<T*>::iterator i = begin(); i != end(); ++i) {
                    if (dynamic_cast<K*>(i) != nullptr) {
                       PrintThatObject(i);    //<------- There i call it
                    }
                }
            }

          //<------- How this method shoud look? ------>
            void PrintThatObject(int i) {
                std::cout << i;
            }
        };

    int main() {
        Foo<int*> f;
        f.PrintSpecificObject<int>(f.PrintThatObject); // Error C3867
        f.PrintSpecificObject<int>(&Foo<int*>::PrintThatObject); // Error C2664
      //  <------- Or How should i call that method?  -------> 
  }

You can't pass any representation of PrintThatObject to PrintSpecificObject.您不能将 PrintThatObject 的任何表示形式传递给 PrintSpecificObject。 The problem is that PrintSpecificObject takes a function pointer.问题是 PrintSpecificObject 需要一个函数指针。 PrintThatObject is a member function. PrintThatObject 是一个成员函数。 Huge difference ! 巨大的差异

You could fix PrintSpecificObject, or just add an overload and it won't be ambiguous, like so:您可以修复 PrintSpecificObject,或者只是添加一个重载,它不会模棱两可,如下所示:

template < typename Object, typename K >
void PrintSpecificObject(Object * o, void (Object::*fun)(K*))
{
    //...whatever...
    // call function
    o->*fun(some_k);
}

You'd call with f.PrintSpecificObject<int>(&Foo<?>::PrintThatObject)你会打电话给f.PrintSpecificObject<int>(&Foo<?>::PrintThatObject)

The ?这 ? is whatever type you passed to Foo to instantiate the class for f.是您传递给 Foo 以实例化 f 类的任何类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM