Is there a way to detect portably that a standard header is included using macros?

两盒软妹~` 提交于 2019-12-05 03:51:00

One option you have it to make your overload a "worse match" than the alternatives. Then, only if they don't already exist will your version be selected:

#if 0
#include <algorithm>
using std::swap;
#endif

template <typename T>
struct ForceLessSpecialized {
  typedef T TYPE;
};

template <typename T>
void swap (T &, typename ForceLessSpecialized<T>::TYPE &) {
}

void bar () {
  int i;
  swap (i, i);
}  

What's happening:

When there are two candidate function template specializations, the compiler performs "Partial ordering of function templates"('03 14.5.5.2). This checks if the function template parameters of the one template can be used to specialize the other.

For each template we'll use dummy parameters T1 and T2 and we create dummy argument lists using these types:

// std::swap argument list
( T1 &  , T1 & )

// our swap argument list
( T2 &, typename ForceLessSpecialized<T2>::TYPE & )

Specializing our swap using the dummy arguments from std::swap gives:

Deduction from First parameter:  T == T1
Deduction from Second parameter:  Non Deduced Context

The deduced T is T1 and deduction has succeeded.

Specializing std::swap using the dummy arguments for our swap gives:

Deduction from First parameter:  T == T2
Deduction from Second parameter:  T == ForceLessSpecialized<T2>::TYPE

The deduced types for T are not the same, and so this is considered a deduction failure.

Therefore, the synthesized arguments of std::swap can be used to specialize our template, but the synthesized arguments of our template cannot be used to specialize std::swap. std::swap is seen as being more specialized and so wins the partial ordernig.

C++17 brought a new feature that now makes this possible is relevant.
https://en.cppreference.com/w/cpp/preprocessor/include

it's called __has_include
example here: #if __has_include(<algorithm>)

EDIT: it's different from the requirement of the question though, it just tells reachability.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!