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

c – 将函数指针作为模板参数传递,第1张

概述出于教育目的,我正在尝试编写自己的“ForEach”函数: #include <iostream>#include <string>#include <vector>//// This works//template<class Container>void ForEach_v1(const Container & inContainer, void (*Functor)(con 出于教育目的,我正在尝试编写自己的“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::allocator<char> > > >,Functor = voID (*)(const std::string&)]':main.cpp|116| instantiated from heremain.cpp|96| warning: unused variable 'it'

节目输出:

v1onetwothreev2

我的问题:

>为什么ForEach_v2不打印任何东西?
>为什么编译器会为ForEach_v2打印“未使用的变量” – 警告?

解决方法 你要

inFunctor(*it);

Functor(*it);
总结

以上是内存溢出为你收集整理的c – 将函数指针作为模板参数传递全部内容,希望文章能够帮你解决c – 将函数指针作为模板参数传递所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1220446.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存