包装模板函数和<未解析的重载函数类型 [英] wrapping template function and <unresolved overloaded function type

查看:61
本文介绍了包装模板函数和<未解析的重载函数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的包装功能有问题.

template <typename Iter, typename SomeFunction>                         
void wrap(Iter first, Iter last, SomeFunction someFunction)
{
  someFunction(first, last);
}

我想这样使用它:

template <typename Iter>
void fill5(Iter first, Iter last)
{
    fill(first, last, 5); 
}
int main()
{
    vector<int> v(100, -1);
    wrap(v.begin(), v.end(), fill5);

}

但是我明白了

test.cpp: In function ‘int main()’:
test.cpp:16:40: error: no matching function for call to ‘wrap(std::vector<int>::iterator, std::vector<int>::iterator, <unresolved overloaded function type>)’
test.cpp:16:40: note: candidate is:
wrap.h:6:6: note: template<class Iter, class SomeFunction> void wrap(Iter, Iter, someFunction)

我知道是否可以像这样调用该函数

I know that if I will call that function like this

wrap(v.begin(), v.end(), fill5< vector<int>::iterator> );

它将编译.但是,我是否总是必须明确地做到这一点?糟透了.为什么编译器无法推断将使用哪个函数?是否有可能编写包装函数以像第一个一样接受参数?

it will compile. But do I always have to do it explicit? It's sucks. Why compiler can't deduce which function will be used? Is there any possibility to write wrap function to take arguments like in the first one?

推荐答案

由于fill是模板函数,因此基本上有无限数量的重载,并且编译器不知道选择哪个重载.

Because fill is a template function, there are basically an infinite number of overloads and the compiler does not know which one to choose.

如果您声明第二个模板参数来描述一个采用2个Iter类型参数的函数,则可以推断出它.下面的示例有效,并且看起来像您想要的.它不像您尝试的那样通用.这样可以确保要调用的函数返回void并采用2个Iter参数.

If you declared your second template parameter to describe a function that took 2 parameters of type Iter it could then deduce it. The example below works and looks like what you want. It is not quite as generic as your attempt. It ensures the function to be called returns void and takes 2 Iter paramters.

template <typename Iter >
void wrap( Iter first, Iter last, void(*someFunction)(Iter,Iter) )
{
someFunction( first, last );
}

template <typename Iter>
void fill5(Iter first, Iter last)
{
    fill(first, last, 5); 
}

int main( int, char ** )
{
std::vector<int> v(100, -1);
wrap(v.begin(), v.end(), fill5);

return( 0 );
}

这篇关于包装模板函数和&lt;未解析的重载函数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆