如何从函数类型自动推断返回类型
How to automatically infer the return type from a function type?
我正在使用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的新特性可能会引起人们的兴趣。
相关文章:
- 访问者访问变体并返回不同类型时出错
- 我的模板类方法返回错误类型?
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 为什么函数名不能与返回名类型相同?
- 如何在模板中返回正确类型的数据?
- 返回派生类型时出现协变类型错误
- 当你只使用 return 时,函数返回什么类型;在 c++ 中
- 函数的返回值类型是别名 ***或 *** 布尔值
- 有没有办法改变概念中的复合需求返回的类型?
- 在C++如何从数组中提取成员并返回成员类型的数组?
- 如何在 c++ 中从 switch 语句返回不同类型的变量
- C++如何使虚拟函数返回任何类型的指针
- 返回各种类型的函数的SWIG类型映射
- 如何为返回特定类型的函数创建 SWIG 类型图
- 更改 Python 切换的 C 函数的返回值类型
- 如何修复用于根据参数返回不同类型的模板类中的错误C2679?
- 为什么我的函数不返回点类型?
- 如何返回 QVariant 类型数组
- 用 decltype 和 auto 推导出 const(返回)类型
- 元函数使用 decltype 返回元素类型