如何从函数类型自动推断返回类型

How to automatically infer the return type from a function type?

本文关键字:返回类型 类型 函数      更新时间:2023-10-16

我正在使用boost::python创建C++库的Python包装器。在某种程度上,boost::python需要一个指向成员函数(或兼容的函数)的指针,如:

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);

由于我正在包装的类具有以下形式的setter:

template <class MyClass, typename ValueType>
MyClass& (MyClass::*setter_method)(ValueType)

我写了一个"转换"函数:

template <typename MyClass, typename ValueType, setter_method<MyClass, ValueType> fluent_setter>
void nonfluent_setter(MyClass& instance, ValueType value)
{
  (instance.*fluent_setter)(value);
}

我可以这样使用:

class Foo
{
  public:
    Foo& bar(int value);
};
my_boost_python_call(nonfluent_setter<Foo, int, &Foo::bar>);

到目前为止,它运行良好,但我想知道是否有办法让它更"容易"(使用)。

你认为有可能得到这样的东西吗:

// 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));

欢迎所有的解决方案(甚至是解释如何专门化boost::python来处理我的特定案例的解决方案)。

谢谢。

实际上可以使用强制转换运算符推断函数的返回类型——我在这里描述了这一点。

这是简短的版本:

struct ReturnType {
  template<typename T>
  operator T() {
    // your code for return a T goes here.
  }
};
ReturnType func() { return ReturnType(); }

在这里,编译器将推断T的值,因此也推断出func的返回类型。

在C++中不能自动推导返回类型,也不能基于返回类型重载函数。

在C++0x中,有一个名为decltype的新特性可能会引起人们的兴趣。