How to automatically infer the return type from a function type?
I'm using boost::python
to create a Python wrapper of a C++ library. At some point, boost::python
needs a pointer to a member function (or something compatible), like:
template <class MyClass, typename ValueType>
void (*setter_function)(MyClass&, ValueType)
// This doesn't compile, but you got the idea.
my_boost_python_call(setter_function f);
Since the class I'm wrapping has its setter in the following form:
template <class MyClass, typename ValueType>
MyClass& (MyClass::*setter_method)(ValueType)
I wrote a single "conversion" function:
template <typename MyClass, typename ValueType, setter_method<MyClass, Val开发者_高级运维ueType> fluent_setter>
void nonfluent_setter(MyClass& instance, ValueType value)
{
(instance.*fluent_setter)(value);
}
Which I can use like that:
class Foo
{
public:
Foo& bar(int value);
};
my_boost_python_call(nonfluent_setter<Foo, int, &Foo::bar>);
So far this works well, but I wonder if there is a way to make this even more "easy" (to use).
Do you think it is somehow possible to get something like:
// return type is somehow inferred from the member function pointer
my_boost_python_call(nonfluent_setter<Foo, &Foo::bar>);
// or even a syntax similar to boost::python::make_function
my_boost_python_call(make_nonfluent_setter<Foo>(&Foo::bar));
All solutions (even ones that explain how to specialize boost::python
to handle my specific case) are welcome.
Thank you.
It is actually possible to infer the return type of a function using casting operators -- I describe this here.
Here's the short version:
struct ReturnType {
template<typename T>
operator T() {
// your code for return a T goes here.
}
};
ReturnType func() { return ReturnType(); }
Here, the compiler will infer the value of T
, thus the return type of func
is also inferred.
The return type cannot be automatically deduced in C++ and you cannot overload functions based on return type.
In C++0x there is a new feature called decltype that might be of interest.
精彩评论