Function argument type

≡放荡痞女 提交于 2019-12-22 11:16:58

问题


My code is supposed is to determine if the given function takes the given type as a parameter. Answering your future "what for" questions I will shortly answer: to use it with boost::enable_if template.

The code uses decltype operator of the C++11. My question is: Is it possible to achieve the same goal using 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;

}

The error is:

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

回答1:


I think you can do this by means of Boost.FunctionTypes, or also you can use boost type traits.

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


来源:https://stackoverflow.com/questions/15644611/function-argument-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!