如何将二进制函数传递给模板函数C ++

时间:2016-12-15 13:40:13

标签: c++ c++11 templates stl std

我想将标准化的C ++二进制函数传递给模板函数,但不知怎的,我没有让它工作。

以下是我的尝试:

template<template <typename> typename Pred,typename T, typename Iterator>
void iota_stepa(Iterator begin, Iterator end, T startofSequence_, T threadStep)
{
    int currMaxThreads = startofSequence_;
    bool first = true;
    generate(begin, end,  Pred<T>(currMaxThreads, threadStep) );
}

并用以下方法进行测试:

vector<int> tempVect_(10, 0);

iota_stepa<std::plus>(begin(tempVect_),end(tempVect_),1,thread::hardware_concurrency());
不幸的是,

给了我错误:

Severity    Code    Description Project File    Line    Suppression State
Error   C2440   '<function-style-cast>': cannot convert from 'initializer list' to 'std::plus<int>'
Error   C2672   'generate': no matching overloaded function found   FractalCarpet   
Error   C2780   'void std::generate(_FwdIt,_FwdIt,_Fn0)': expects 3 arguments - 2 provided  FractalCarpet

控制台输出如下所示:

1>  c:\users\mtunca\documents\esd\sps\fractalcarpet\main.cpp(55): note: see reference to function template instantiation 'void iota_stepa<std::plus,int,std::_Vector_iterator<std::_Vector_val<std::_Simple_types<float>>>>(Iterator,Iterator,T,T)' being compiled
1>          with
1>          [
1>              Iterator=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<float>>>,
1>              T=int
1>          ]
1>c:\users\mtunca\documents\esd\sps\fractalcarpet\main.cpp(34): error C2672: 'generate': no matching overloaded function found
1>c:\users\mtunca\documents\esd\sps\fractalcarpet\main.cpp(34): error C2780: 'void std::generate(_FwdIt,_FwdIt,_Fn0)': expects 3 arguments - 2 provided
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm(1532): note: see declaration of 'std::generate'

有人可以帮助我,如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

std::generate需要一个生成器,可以像gen()一样调用。 你可以用lambda创建一个,也许是这样的:

template<template <typename> class Pred, typename T, typename Iterator>
void iota_stepa(Iterator begin, Iterator end, T startofSequence_, T threadStep)
{
    bool first = true;
    T current;
    auto gen = [&]() -> T
    {
        if(first) {
            current = startofSequence_;
            first = false;
        } else {
            current = Pred<T>() ( current, threadStep );
        }
        return current;
    };
    generate(begin, end, gen );
}

答案 1 :(得分:0)

Pred<T>(currMaxThreads, threadStep) );

Pred<T>是一种类型。您需要构造一个实际的可调用对象:

Pred<T>()(currMaxThreads, threadStep) );

然而,这不是std::generate的最后一个参数。后者需要一个没有参数的可调用对象,可能持有一个状态(否则调用std :: fill woud就足够了)。目前还不清楚如何调整任意二元函数来填补这一角色。