STL 函数 / 提升函数类型定义错误
STL function / Boost function typedef errors
我正在尝试弄清楚如何根据我正在编译它的平台在 boost 函数和 c++11 函数之间切换。我知道 c++ 没有模板别名(pre-c++11),所以我写了以下内容,但我无法理解错误消息或为什么它不起作用:
#define FUNCTION_Boost
#if defined(FUNCTION_Boost)
#include <boost/function.hpp>
#elif defined(FUNCTION_STL)
#include <functional>
#endif
template<typename Res, typename... ArgTypes>
struct function {
#if defined(FUNCTION_Boost)
typedef boost::function<Res(ArgTypes...)> type;
#elif defined(FUNCTION_STL)
typedef std::function<Res(ArgTypes...)> type;
#endif
};
// In instantiation of ‘function<void()>’:
// error: function returning a function
void foo(function<void ()>::type f) {
f();
}
// this works fine
void bar(boost::function<void ()> f) {
f();
}
无需
再定义一个function
...一切都可以使用using
;)来完成
#define USE_BOOST_FUNCTION
#ifdef USE_BOOST_FUNCTION
# include <boost/function.hpp>
# define FUNCTION_NS boost
# else
# include <functional>
# define FUNCTION_NS std
# endif
#include <iostream>
namespace test {
using FUNCTION_NS::function;
}
int main()
{
test::function<void()> f = [](){ std::cout << __PRETTY_FUNCTION__ << std::endl; };
f();
return 0;
}
我的印象是这段代码没有做你认为它做的事情:
typename function<void ()>::type
绑定"void ()"作为 Res 只是创建一个返回函数的函数。
怎么样:
...
void foo(typename function<void >::type f) {
f();
}
...
?
你可以得到类似于你试图通过boost::type_traits和boost::type_traits::function_traits获得的别名。也就是说,我怀疑如果你想要一个简单而可移植的解决方案,那么最简单的方法是使用 boost 并等待更好的时间与 C++ 编译器和 C++11 的 STL 支持。
相关文章:
- 不同翻译单元中不可重载的非内联函数定义
- Visual Studio中的函数声明和函数定义问题
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 具有enable_if外部类原型的模板类构造函数定义
- 类的前向声明之后的类成员函数定义,在类声明之前
- 为函数定义符号不明确的指针参数
- C++模板专用化 - 无法匹配函数定义
- 错误:在第 6 行'{'标记之前,此处不允许使用函数定义
- 找不到 #define 的函数定义
- 根据类型特征更改函数定义?
- 将抽象基类中的所有纯虚函数定义为 varaidaic 模板
- 命名空间更改函数定义
- "Type&"与C++函数定义中的"Type*"
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 如何从 C++ 中的现有模板函数定义新函数
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- 为什么c++允许成员函数定义中实例的私有成员访问
- Qt基类函数定义
- C++函数定义中参数列表后面额外一对括号的含义