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
4

1 回答 1

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;
}
于 2013-03-26T19:11:41.787 回答