函数参数类型

问题描述:

我的代码应该是确定给定函数是否将给定类型作为参数。回答你的未来“我为什么”的问题,我将很快回答:与boost::enable_if模板一起使用。函数参数类型

该代码使用C++ 11的decltype运算符。我的问题是:是否可以使用c + + 03来实现相同的目标?

#include <iostream> 

template <class F, class P> 
struct has_arg_of_type 
{ 
    static bool const value = false; 
}; 

template <class R, class A> 
struct has_arg_of_type<R (A), A> 
{ 
    static bool const value = true; 
}; 

template <class R, class T, class A> 
struct has_arg_of_type<R (T::*)(A), A> 
{ 
    static bool const value = true; 
}; 

int pisz(int); 

class MyClass 
{ 
public: 
    void pisz(int); 
}; 

int main(int argc, char *argv[]) 
{ 

    std::cout << "MyClass::pisz has the int as an argument? " << has_arg_of_type<decltype(&MyClass::pisz), int>::value << std::endl; // Line 32 
    std::cout << "pisz has the int as an argument? ? " << has_arg_of_type<decltype(pisz), int>::value << std::endl; 
    std::cout << "pisz has the float as an argument? ? " << has_arg_of_type<decltype(pisz), float>::value << std::endl; 

    return 0; 

} 

的错误是:

In function 'int main(int, char**)': 
Line 32: error: 'MyClass::pisz(int)' cannot appear in a constant-expression 
+0

是的,我知道有一个错误。我认为这个键盘(最初是我用来编码的)不支持C++ 11。但代码编译在MinGW-32 Qt 5.0(IIRC g ++ 4.6) – user2146414 2013-03-26 19:41:13

我想你可以通过Boost.FunctionTypes手段做到这一点,或者你也可以使用升压型特征。

+0

感谢您的回复!我认为你的代码的关键部分是BOOST_TYPEOF。我希望有一些容易实现的方法(不涉及提升)。不过,我可以用C++ 03获得我想要的。 – user2146414 2013-03-26 19:35:59

+0

因为它已经解决了你的问题,你至少可以标记已解决和upvote! :) – 2013-03-27 12:44:16

+0

我厌倦了upvote,但我的名声太低:(而且我对这个论坛很新颖:检查你的答案是一个可接受的答案是你的吗? – user2146414 2013-03-27 21:54:05