加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:28:30 所属栏目:百科 来源:网络整理
导读:出于教育目的,我正在尝试编写自己的“ForEach”函数: #include iostream#include string#include vector//// This works//templateclass Containervoid ForEach_v1(const Container inContainer,void (*Functor)(const std::string )){ typename Container:
出于教育目的,我正在尝试编写自己的“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 here
main.cpp|96| warning: unused variable 'it'

节目输出:

v1
one
two
three
v2

我的问题:

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

解决方法

你要

inFunctor(*it);

Functor(*it);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读