开发者

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: 'IsF开发者_如何学Pythonunc' : 'functionA' is not a valid template type

What am I doing wrong?

Thanks


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).


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


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜