简体   繁体   English

ptr_fun-无法创建类型?

[英]ptr_fun - can't create a type?

How can i do some thing like: 我该如何做这样的事情:

#include <functional>

#include <boost/functional.hpp>

int foo(int){return 1;};

template<typename T>
int bar(T t)
{
  return 10;/*or something*/
}

int main() {

  bar<   std::ptr_fun<int, int>(foo) > (1);
  bar< boost::ptr_fun<int, int>(foo) > (1);

  return 0;
}

In both ptr_fun-lines i got error C2974: 'bar' : invalid template argument for 'T', type expected . 在这两个ptr_fun行中,我都收到error C2974: 'bar' : invalid template argument for 'T', type expected As far as i know prt_fun creates a type, but std::ptr_fun<int, int>(foo) creates an object. 据我所知prt_fun创建一个类型,但std::ptr_fun<int, int>(foo)创建一个对象。 Is there way to create a type "initialized" with function pointer usinf as much std as possible? 有没有办法用函数指针usinf尽可能多地创建一个“初始化”类型的std?

Probably could solve this by manualy coding an functor, but i belive there is the ptr_fun-way. 可能可以通过手动编码函子来解决此问题,但我相信这里有ptr_fun-way。

ptr_fun returns an object of type pointer_to_unary_function . ptr_fun返回类型为pointer_to_unary_function的对象。 You declared your template to take a type parameter, so passing it an object clearly won't work. 您已声明模板采用类型参数,因此将对象传递给它显然不起作用。

You could make it work like this (note you don't need to specify the template parameter, it can be deduced by the compiler): 您可以像这样使它工作(请注意,您无需指定template参数,它可以由编译器推导):

#include <iostream>
#include <functional>

int foo(int i)
{
    return i;
}

template<typename TResult, typename TArg>
int bar(std::pointer_to_unary_function<TArg, TResult> p, TArg arg)
{
    return p(arg);
}

int main()
{
    std::cout << bar(std::ptr_fun<int, int>(foo), 42);
}

But you don't really need ptr_fun . 但是您实际上并不需要ptr_fun You could simply do it like this: 您可以像这样简单地做到这一点:

#include <iostream>
#include <functional>

int foo(int i)
{
    return i;
}

template<typename TFunc, typename TArg>
int bar(TFunc f, TArg arg)
{
    return f(arg);
}

int main()
{
    std::cout << bar(foo, 42);
}

Or, to make it work like you set it up: 或者,要使其像您设置的那样工作:

int foo(int i) { return i; }

template<typename T>
int bar(T t)
{
    t(42);
}

int main() {
  std::cout << bar( std::ptr_fun<int, int>(foo) );
}

Lots of quesswork, becase it's not really clear what you're trying to accomplish. 很多任务,如果不清楚您要完成什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM