C++ STL函数/升压函数类型定义错误
我试图找出如何根据编译它的平台的可用性在boost函数和c++11函数之间切换。我知道C++没有模板混叠(前C ++ 11),所以我写了下面的,但是我不能理解错误消息或者它为什么不工作:< /P>C++ STL函数/升压函数类型定义错误,c++,templates,alias,typedef,C++,Templates,Alias,Typedef,我试图找出如何根据编译它的平台的可用性在boost函数和c++11函数之间切换。我知道C++没有模板混叠(前C ++ 11),所以我写了下面的,但是我不能理解错误消息或者它为什么不工作:< /P> #define FUNCTION_Boost #if defined(FUNCTION_Boost) #include <boost/function.hpp> #elif defined(FUNCTION_STL) #include <functional> #
#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();
}
#定义功能#
#如果已定义(功能_Boost)
#包括
#定义的elif(功能\u STL)
#包括
#恩迪夫
模板
结构函数{
#如果已定义(功能_Boost)
typedef boost::函数类型;
#定义的elif(功能\u STL)
typedef std::函数类型;
#恩迪夫
};
//在“函数”的实例化中:
//错误:函数返回函数
void foo(函数::类型f){
f();
}
//这个很好用
空栏(boost::函数f){
f();
}
我的印象是,这段代码并不像您想象的那样:
typename function<void ()>::type
typename函数::type
将“void()”绑定为Res,只是创建一个返回函数的函数
那么:
...
void foo(typename function<void >::type f) {
f();
}
...
。。。
void foo(typename函数::type f){
f();
}
...
?
您可以使用boost::type_traits和boost::type_traits::function_traits获得类似的别名。也就是说,我怀疑如果你想要一个简单的和可移植的解决方案,那么最简单的做法是使用Boost和等待更好的时间用C++编译器和STL支持C++ 11。一切都可以使用
和;)来完成
#定义使用增强功能
#ifdef使用_BOOST_功能
#包括
#定义函数
#否则
#包括
#定义函数
#恩迪夫
#包括
名称空间测试{
使用FUNCTION\u NS::FUNCTION;
}
int main()
{
测试::函数f=[](){std::cout错误消息是什么?如果它给出了一个行号,请告诉我们这是哪一行。@BenjaminLindley:它在代码的注释中。嗯,我仍然得到了相同的错误。第二个示例使用的是boost::function绑定正确。这解决了我的问题,但你知道我为什么得到错误消息吗?很幸运(或者可能是有意的)std::function和boost::function具有相同的模板参数;我知道这不适用于线程或互斥。
#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;
}