On Tuesday, 30 June 2015 18:19:11 UTC+1, Paul wrote:
> I am trying to write two versions of Quicksort, one that uses randomised partition, and one that doesn't randomise the partition. However, I want them to have signatures std::vector<int> f(std::vector<int> vec) and so I want to bind the quicksorts to Boolean parameters.
>
> I can't find the syntax to do this though. Just so that I haven't left out any context, I will copy-paste my entire code. However, I will mark out the offending line with asterisks.
> Many thanks for your help.
<snip>
std::vector<int> QuickSort(std::vector<int> vec, bool random = false)
> {
<snip>
> }
>
> // Use bind concept to distinguish the two types of Quicksort without repeating code.
> /*****************************************************************************************************
> Below is meant to declare the variant of QuickSort that uses bool random = false but I can't find the syntax.
> ************************************************************************************************************
> *************************************************************************************************************
> Below line gives compile error! */
> std::vector<int>(*QuickSortBasic)(std::vector<int>) = std::bind(QuickSort, std::placeholders::_2, false);
<snip>
std::bind() returns an object encapsulating enough information
to call your QuickSort function with the correct set of parameters
when it is "called" (i.e. it passes the parameter passed in the
call and the parameter given to std::bind()).
As such, it is a functional object (a "functor") and definitely
not a function pointer. Furthermore, the Standard tells us that
the type of that object is unspecified, so you cannot write its
type out in your declaration of QuickSortBasic. So just use
auto QuickSortBasic = std::bind(QuickSort, std::placeholders::_2, false);
instead, which is so much neater anyway.
If you *really* want to avoid using 'auto' and spell out the type
of the binder object, you'll need to resort to using the deprecated
bind2nd() binder, thus:
std::binder2nd<
std::pointer_to_binary_function<
std::vector<int>, bool, std::vector<int> > >
QuickSortBasic = std::bind2nd(std::ptr_fun(QuickSort), false);
However, apart from the issue of these binders being deprecated,
I'm sure you'll agree that this is a particularly ugly solution.
Like the rest of us, be thankful for 'auto' and std::bind().