教育目的我試圖寫我自己 「的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
?
尷尬... – StackedCrooked 2010-12-09 19:54:56