Is there a way to find out what the return type of a function (or even better of a function pointer) is ?
I've got the follow开发者_JS百科ing code, which breaks when I use a void function pointer, but works fine for any other return type. The error I get when using a void function pointer from gcc 4.5 is:
error: void value not ignored as it ought to be
Which makes sense. So obviously I need to check if function pointer returns something, and then obtain the result and return it.
template <class F,typename R> class Instruction
{
protected:
F (func);
R result;
public:
template <typename T>
Instruction(T const& f)
{
func = &f;
};
template <typename A> void execute(A const& a)
{
result = (func)(a);
};
template <typename A> void execute(A const& a,A const& b)
{
result = (func)(a,b);
};
template <typename A> void execute(A const& a,A const& b,A const& c)
{
result = (func)(a,b,c);
};
R get_result()
{
return result;
};
};
Normally I use a function pointer to a function which does something mostly arithmetic and I can take care of any return type at instantiation other than void functions. I've tried instantiating as:
Instruction<ptr2func2,void> foo(bar);
Instruction<ptr2func2,(*void)> foo(bar);
but in both cases it fails.
The second template argument at instantiation is used in order to define what the return type will be.
Try a template partial specialization on void
:
template <class F> class Instruction<F, void>
{
protected:
F (func);
public:
template <typename T>
Instruction(T const& f)
{
func = &f;
};
template <typename A> void execute(A const& a)
{
(func)(a);
};
template <typename A> void execute(A const& a,A const& b)
{
(func)(a,b);
};
template <typename A> void execute(A const& a,A const& b,A const& c)
{
(func)(a,b,c);
};
};
You may want to use Boost::FunctionTypes which provide a metafunction able to decompose function type and give you access to the return or argument type.
In C++0x you can decltype
. However, in C++03, by convention, function objects have a result_type
typedef, and function pointers can have template deduction applied to them.
精彩评论