Detecting if type is a function

template<class T>
struct IsFunc
{
    typedef char one;
    typedef struct 
    {
        char dummy_[2];
    } two;

    static one f(...);

    static two f(T (*)[1]);
    enum {value = (sizeof(f<T>(0)) == 1)};
};

And if I try to run it in main:

void functionA();
    int _tmain(int argc, _TCHAR* argv[])
    {
        int a = 0;
        cout << IsFunc<functionA>::value;//<=--------HERE

        return 0;
    }

I'm getting an error:
Error 1 error C2923: 'IsFunc' : 'functionA' is not a valid template type
What am I doing wrong?
Thanks

Upvotes: 1

Views: 142

Answers (3)

Others already stated the reason but would this help you?

#include <type_traits>
#include <typeinfo>
namespace
{
   template<typename T>
   bool test_if_function (T const &v)
   {
      return std::tr1::is_function<T>::value;
   }

   void functionA()
   {
   }
}

int main()
{
   printf ("%d\r\n", test_if_function (1));
   printf ("%d\r\n", test_if_function (functionA));

   return 0;
}

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

If you have template<class T> class X; you don't expect X<3> to work and deduce that T is int, do you? The same is here IsFunc<FunctionA> is invalid, but IsFunc<void()> is fine. HTH

Upvotes: 1

kennytm
kennytm

Reputation: 523294

functionA is a function, not a type, so it cannot be a valid template parameter to IsFunc which expects a type.

If you need a template to detect whether a type is a function type, there is already boost::is_function (which is part of TR1/C++0x).

Upvotes: 3

Related Questions