gpt4 book ai didi

c++ - STL 函数/Boost 函数类型定义错误

转载 作者:行者123 更新时间:2023-11-30 04:21:22 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何根据我正在编译它的可用平台在 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();
}

最佳答案

无需再定义一个函数...一切都可以使用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;
}

关于c++ - STL 函数/Boost 函数类型定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14545297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com