user2935354
user2935354

Reputation:

Function pointer in Template

In a old code I am seeing function pointer is used in template:

typedef int (*get_max)();

template<get_max FUNC>
get_max func()
{
        return FUNC;
}

As I am new to template, I am lost and trying to google for more same theories how this is possible. Any link of book where this is described? Thanks in advance

Upvotes: 5

Views: 189

Answers (1)

gwiazdorrr
gwiazdorrr

Reputation: 6329

Global functions have known addresses of known sizes, so they can be used in compile-time expression, e.g. as template parameters. On standard x86 platforms that address has 32 bits, on x64 - 64 bits (that's why for storing it you shouldn't use int, which has 32 bits on both platforms, but rather intptr_t).

So what the code is doing is returning a pointer to a function the func function has been specialised for. Internally, it simply returns an address of passed function. What may have confused you is that function names decay to function pointers (i.e. you don't have to use & to get function's address)

You can also create a template with a parameter being an address of a global non-static variable, if you are in these kind of things. It helps to understand what's going on in your original example.

#include <iostream>
#include <string>

template<int* p>
int* useless_proxy()
{
    return p;
}

int foo = 666;

int main()
{
    std::cout << *useless_proxy<&foo>() << std::endl; // prints 666
};

Upvotes: 1

Related Questions