简体   繁体   中英

result_of type trait in C++03

Is the result_of type trait implementable with pre C++11 tools?

No need for variadic arguments, static implementations for 1, 2, 3 ... args will suffice

attempts

I know that I can do this

template<typename Ret, typename Arg, Ret (F)(Arg)>
struct result_of1 // result of unary function
{
    typedef Ret type;  
};

int func(int&); 
result_of1<int, int&, func>::type a; 

From here it seems that if I had a way to defer the func , say a deducable context, an extra layer, I would be able to pass a function and split it to its components : return type, arg type, and function type just by using the function type.

Unluckily the class specialization process does not pose a deducable context ie I can't do the following

template<>
struct result_of1<Ret F(Arg), Ret, Arg> {}; 

provide just the F and have the rest deduced, so maybe filtering the type through an argument to a function would be a solution but I can't get my mind around it.

No.

result_of takes a type F and a set of arguments to pass to F (Args...) . It then determines what the type you get from std::declval<F>()(std::declval<Args>()...) .

While you can create fixed arg-count versions of it for each arg count, you cannot find the type of an expression in C++03 and use it elsewhere.

Attempts to do so can involving taking function pointer and function reference and function types and unpacking their type do get you part way there. But invokable objects can contain multitudes of overloads.

A bargain-basement version would just take the address of operator() and, assuming it has no overloads and is not a template method, can deduce the return type.

However, in every case, the (Args...) portion is useless, other than the possibility to check if the Args... are valid parameters.

The point of result_of is being able to do full dispatch at compile time and determine which of the overloads are used, and give us the return type from that overload. This cannot be done in C++03.

Use template specialization:

template <typename Func>
struct result_of;

template <typename Ret>
struct result_of<Ret()>
{
    typedef Ret ret;
};

template <typename Ret, typename P1>
struct result_of<Ret(P1)>
{
    typedef Ret ret;
    typedef P1 p1;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM