ITeye博客

template学习:一个Functor的使用例子

ah_fu · 2008-01-12 18:52 · C · C++ · C# · Markdown


#include <stdio.h>

// 模板,可以调用函数或者Functor
template <typename Functor>
void TestTemplate(Functor func)
...{
    func("TestTemplate");
}

// C函数风格
void TestFunction(const char* str)
...{
    printf("TestFunction:%s ", str);
}

// Functor风格
struct TestFunctor
...{
    void operator()(const char* str)
    ...{
        printf("TestFunctor:%s ", str);
    }
    TestFunctor()
    ...{
        printf("TestFunctor() ");
    }
    ~TestFunctor()
    ...{
        printf("~TestFunctor() ");
    }
};

int main()
...{
    TestTemplate(TestFunction);  //函数指针作为调用参数
    printf("========================================== ");
    TestTemplate( TestFunctor() );  //Functor临时对象作为调用参数
    printf("========================================== ");
    TestFunctor obj;  //生成一个Functor的实例
    TestTemplate<TestFunctor&>(obj);  //使用引用类型来调用,避免拷贝
    return 1;
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。