出于教育目的,我正在尝试编写自己的“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
打印“未使用的变量” - 警告?答案 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!
}
现在这将有效!