gpt4 book ai didi

c++ - 基于宏的 C++ 头文件选择

转载 作者:行者123 更新时间:2023-11-28 01:09:01 24 4
gpt4 key购买 nike

我目前正在编写一个 C++ 库,需要用 GCC 为 linux 和 Sun CC 为 Solaris 编译。为了提高性能,我正在创建一些类,这些类根据编译器选择不同的 header ;使用 c++0x 或 TR1 或使用 niether 和 Sun CC RogueWave 或 STLPort 的 GCC。我正在努力找出 #ifdef'ing typedef 的最佳方法,例如:

namespace project {

#if defined(__GNUG__)
#if defined(HAVE_CXXOX)
#include <unorderd_map>
typedef srd::unordered_map map;
#elif defined(HAVE_TR1)
#include <tr1/unordered_map>
typedef std::tr1::unordered_map map;
#else
#include <map>
typedef std::map map;
#endif
#elif defined(__SUNPROC_CC)
#include <map>
typedef std::map map;
#endif

} //namespaces

最佳答案

这行不通有两个原因:

  1. header 必须包含在 namespace project { ... } 的范围之外。 (如果 header 只包含模板和内联函数,它可能仍然有效,但我不会指望它。)
  2. typedef 不适用于模板。有一个解决方法,您可以定义一个空的派生类。

所以也许是这样的:

#if defined(__GNUG__)
#if defined(HAVE_CXXOX)
#include <unordered_map>
#define MAP std::unordered_map
#elif defined(HAVE_TR1)
#include <tr1/unordered_map>
#define MAP std::tr1::unordered_map
#else
#include <map>
#define MAP std::map
#endif
#elif defined(__SUNPROC_CC)
#include <map>
#define MAP std::map
#endif

namespace myproject {
template <class K, class V>
class map : public MAP<K, V> {};
}

#undef MAP

关于c++ - 基于宏的 C++ 头文件选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4510109/

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