将函数指针作为模板参数传递

时间:2010-12-09 19:49:14

标签: c++

出于教育目的,我正在尝试编写自己的“ForEach”功能:

#include <iostream>
#include <string>
#include <vector>


//
// This works
//
template<class Container>
void ForEach_v1(const Container & inContainer, void (*Functor)(const std::string &))
{
    typename Container::const_iterator it = inContainer.begin(), end = inContainer.end();
    for (; it != end; ++it)
    {
        Functor(*it);
    }
}


//
// Does not work
//
template<class Container, class Functor>
void ForEach_v2(const Container & inContainer, Functor inFunctor)
{
    typename Container::const_iterator it = inContainer.begin(), end = inContainer.end();
    for (; it != end; ++it)
    {
        Functor(*it);
    }
}

void PrintWord(const std::string & inMessage)
{
    std::cout << inMessage << std::endl;
}

int main()
{
    std::vector<std::string> words;
    words.push_back("one");
    words.push_back("two");
    words.push_back("three");

    // Works fine.
    std::cout << "v1" << std::endl;
    ForEach_v1(words, PrintWord);

    // Doesn't work.
    std::cout << "v2" << std::endl;
    ForEach_v2(words, PrintWord);

    return 0;
}

编译器输出:

|| g++ -Wall -o test main.cpp
|| main.cpp: In function 'void ForEach_v2(const Container&, Functor) [with Container = std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, Functor = void (*)(const std::string&)]':
main.cpp|116| instantiated from here
main.cpp|96| warning: unused variable 'it'

节目输出:

v1
one
two
three
v2

我的问题:

  • 为什么ForEach_v2没有打印任何内容?
  • 为什么编译器会为ForEach_v2打印“未使用的变量” - 警告?

3 个答案:

答案 0 :(得分:8)

你想要

  inFunctor(*it);

  Functor(*it);

答案 1 :(得分:3)

template<class Container, class Functor>
void ForEach_v2(const Container & inContainer, Functor inFunctor)
{
    typename Container::const_iterator it = inContainer.begin(), end = inContainer.end();
    for (; it != end; ++it)
    {
        Functor(*it);
    }
}

应该

template<class Container, class Functor>
void ForEach_v2(const Container & inContainer, Functor inFunctor)
{
    typename Container::const_iterator it = inContainer.begin(), end = inContainer.end();
    for (; it != end; ++it)
    {
        inFunctor(*it);
    }
}

答案 2 :(得分:2)

这是你的问题:

for (; it != end; ++it)
    {
        Functor(*it);
    }

Functor现在是您传递的功能类型

你需要写下这个:

for (; it != end; ++it)
    {
        inFunctor(*it); //note this change!
    }

现在这将有效!