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

时间:2011-06-22 12:25:01

标签: c++ templates metaprogramming boost-python

我正在使用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处理我的具体案例的解决方案)。

谢谢。

2 个答案:

答案 0 :(得分:5)

实际上可以使用强制转换运算符推断函数的返回类型 - 我对此进行了描述here

以下是简短版本:

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

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

答案 1 :(得分:2)

不能在C ++中自动推断返回类型,也不能根据返回类型重载函数。

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

相关问题