Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function argument type

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
like image 864
user2146414 Avatar asked May 06 '26 20:05

user2146414


1 Answers

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;
}
like image 57
Hugo Corrá Avatar answered May 08 '26 10:05

Hugo Corrá



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!