2013-03-26 128 views
3

我的代碼應該是確定給定函數是否將給定類型作爲參數。回答你的未來「我爲什麼」的問題,我將很快回答:與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

回答

1

我想你可以通過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