简体   繁体   中英

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 . As far as i know prt_fun creates a type, but std::ptr_fun<int, int>(foo) creates an object. Is there way to create a type "initialized" with function pointer usinf as much std as possible?

Probably could solve this by manualy coding an functor, but i belive there is the ptr_fun-way.

ptr_fun returns an object of type 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):

#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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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