xmllmx
xmllmx

Reputation: 42371

How to determine if an argument is a pure function pointer?

I want to write a trait-checker named is_pure_func_ptr, which can determine if the type is a pure function pointer, as follows:

#include <iostream>

using namespace std;

void f1()
{};

int f2(int)
{};

int f3(int, int)
{};

struct Functor
{
    void operator ()()
    {}
};

int main()
{
    cout << is_pure_func_ptr<decltype(f1)>::value << endl; // output true
    cout << is_pure_func_ptr<decltype(f2)>::value << endl; // output true
    cout << is_pure_func_ptr<decltype(f3)>::value << endl; // output true
    cout << is_pure_func_ptr<Functor>::value << endl;      // output false
    cout << is_pure_func_ptr<char*>::value << endl;        // output false
}

My question is: How to implement it?

Upvotes: 1

Views: 173

Answers (2)

Grizzly
Grizzly

Reputation: 20191

As stated by Joachim Pileborg, std::is_function will do the job. If that isn't an option for you, but you do have C++11 support (meaning you just want to know how to implement it yourself or your standard library isn't there yet), you could do something like this:

template<typename T>
struct is_pure_func_ptr: public std::false_type {};
template<typename Ret, typename... Args>
struct is_pure_func_ptr<Ret(Args...)>: public std::true_type {};//detecting functions themselves
template<typename Ret, typename... Args>
struct is_pure_func_ptr<Ret(*)(Args...)>: public std::true_type {};//detecting function pointers

This works, but you might need additional work when it comes to supporting functions with different calling conventions and/or cv-qualified pointers

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409196

If you have a C++11 standard library, try std::is_function.

Upvotes: 3

Related Questions