I am working in an environment with many, many header files, into some of which sometimes a using namespace std;
sneaks in. I want to catch (in CI) when that does. It is easy to check that something does exist/compile, but the contrary is surprisingly difficult.
My idea was this:
#include "header1.h"
#include "header2.h"
// ...
static_assert(!type_is_defined(string))
How can I write type_is_defined
such that it compiles when string
is not defined?
This may not be the most elegant way, but it works:
#include <string>
#include <type_traits>
//... many headers here, some of which may contain 'using namespace std;'
//using namespace std; //uncommenting it causes compiler error: "reference to 'string' is ambiguous"
class string;
static_assert(!std::same_as<string, std::string>);
The static_assert
requires C++20 because of same_as
concept. For C++17, you need to replace it with is_same_v
. If you use an earlier C++ version, you can use the following (which works for C++11):
static_assert(!std::is_same<string, std::string>::value, "!");