1 Replies - 13951 Views - Last Post: 29 December 2012 - 07:36 PM

#1 MathiasVP  Icon User is offline

  • D.I.C Head

Reputation: 27
  • View blog
  • Posts: 154
  • Joined: 08-August 10

Alternative implementation of std::ptr_fun

Posted 27 December 2012 - 04:42 PM

Yo people!

I'm playing around with the Visual Studio C++ Nov CTP compiler and came up with an interesting implementation of what ended up being std::ptr_fun (Still working on the return type), but with no need to declare template arguments explicitly. What's your opinion about this implementation?

#include <utility>
#include <iostream>
#include <string>
#include <functional>

class C {
	void* f;
public:
	C(void* g) : f(g) { }

	template<typename... Args>
	void operator()(Args&&... args) {
		typedef void (*F)(Args...);
                //Perfect forwarding to f
		((F)f)(std::forward<Args>(args)...);
	}
};

void g(int i, const std::string& s) {
	std::cout << i << ' ' << s << std::endl;
}

int main() {
	std::string s = "abc";

	//No template stuff
	C c = g;
	c(2, s);

	//Ugly template stuff
	std::pointer_to_binary_function<int, const std::string&, void> f = std::ptr_fun(g);
	f(2, s);

	return 0;
}



Edit: I do know about auto, but let's forget about that for a sec!

This post has been edited by MathiasVP: 27 December 2012 - 04:45 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Alternative implementation of std::ptr_fun

#2 ishkabible  Icon User is offline

  • spelling expret
  • member icon




Reputation: 1622
  • View blog
  • Posts: 5,709
  • Joined: 03-August 09

Re: Alternative implementation of std::ptr_fun

Posted 29 December 2012 - 07:36 PM

your solution provides no type safety. you could call that function by passing it 20 zeros.

the following call would still compile; that's not good
c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);



check out std::mem_fn which is the C++11 replacement for std::ptr_fun.
also check out std::function which is the replacement for pointer_to_binary_function, pointer_to_unary_function, and a lot of other things.

the following is much better.

std::function<void(int, const std::string&)> f = g;
f(2, s);



edit:
the information I gave earlier on mem_fn was wrong. sorry if I caused any confusion. I wasn't reading carefully.

This post has been edited by ishkabible: 30 December 2012 - 09:48 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1