我的代码应该是确定给定的函数是否将给定的类型作为参数。回答你的未来"为什么"问题我将很快回答:与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 :(得分:1)
我认为您可以通过Boost.FunctionTypes执行此操作,或者您也可以使用提升类型特征。
#include <iostream>
#include <boost/function_types/function_type.hpp>
#include <boost/function_types/parameter_types.hpp>
#include <boost/typeof/std/utility.hpp>
float pisz(int);
class MyClass
{
public:
void pisz(int);
};
int main(int argc, char *argv[])
{
typedef BOOST_TYPEOF(&MyClass::pisz) MyClassPisz;
typedef BOOST_TYPEOF(pisz) Pisz;
typedef boost::mpl::at_c<boost::function_types::parameter_types<MyClassPisz>, 1>::type MemberFunction;
typedef boost::mpl::at_c<boost::function_types::parameter_types<Pisz>, 0>::type Function;
std::cout << "MyClass::pisz has the int as an argument? " << boost::is_same<MemberFunction, int>::value << std::endl;
std::cout << "pisz has the int as an argument? ? " << boost::is_same<Function, int>::value << std::endl;
std::cout << "pisz has the float as an argument? ? " << boost::is_same<Function, float>::value << std::endl;
return 0;
}