4

Assuming that & is not overloaded. How to obtain the address of an instantiated template function, such as std::sort<int*>? The following won't compile on some compilers:

#include <algorithm>
int main()
{
    &std::sort<int*>;
}

ON MSVC v19.21, it reports: https://godbolt.org/z/gpZCdn

error C2568: 'identifier': unable to resolve function overload
xuhdev
  • 8,018
  • 2
  • 41
  • 69

2 Answers2

3

You can use

&std::sort<int*>;

&std::sort<int> does not work since the type needs to be dereferenceable.

The ambiguity can be resolved by performing an explicit cast.

static_cast<void (*)(int*, int*)>(&std::sort<int*>);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
3
  • Sort doesn't depend on a type, it depends on an iterator type.
  • There are multiple overloads of std::sort, so you need to help the compiler choose which one via the function prototype.
  • No need to use & to get the address - the name is the address.

Example:

void (*func_ptr)(std::vector<int>::iterator, std::vector<int>::iterator) =
     std::sort< std::vector<int>::iterator >;

std::vector<int> values;
for(int i = 99; i > 0; --i) 
  values.push_back(i);

func_ptr(values.begin(), values.end());

And if you really want int* as your iterator type

void (*func_ptr)(int*, int*) = std::sort<int*>;
robthebloke
  • 9,331
  • 9
  • 12
  • std::sort returns void. You are missing void at the start of the function pointer declaration. See the void in my example above. Just keep in mind that the sort function will work only on the iterator type you have specified. Your simplified example will only work on raw C arrays, and not with lists/vectors/maps etc. – robthebloke Jul 18 '19 at 05:15