【问题标题】:How to automatically infer the return type from a function type?如何从函数类型自动推断返回类型?
【发布时间】:2011-06-22 12:25:01
【问题描述】:

我正在使用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);

由于我要包装的类具有以下形式的设置器:

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

谢谢。

【问题讨论】:

    标签: c++ templates metaprogramming boost-python


    【解决方案1】:

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

    这是简短的版本:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-17
        • 1970-01-01
        • 1970-01-01
        • 2020-03-23
        • 2018-03-03
        • 1970-01-01
        • 1970-01-01
        • 2017-10-15
        相关资源
        最近更新 更多