I have the following code which defines size_t
equivalent to std::size_t
and ::size_t
if I included <cstddef>
.
// h.hpp
namespace N {
using size_t = decltype(sizeof(int));
}
// a.hpp
#include <h.hpp>
namespace N {
class C {
size_t size() const;
};
void f(size_t);
}
// ^^^ These use N::size_t!
Is this violating the C++ standard in any way and can this cause any bugs in any code that uses both these headers and any other standard header that defines std::size_t
and ::size_t
? I would consider it a bug too if someone couldn't use std::size_t
and N::size_t
interchangably in any context or if using just size_t
in any context would cause any ambiguities.
// someOtherFile.cpp
#include <a.hpp>
#include <cstdint>
namespace N {
// Can there be any problem here? (Inside N::)
}
// Or here? (Outside N::)
My guess would be no because both my and the standard size_t
are just type aliases to unsigned long (long) int
I realize that this data type is platform dependent, and is supposedly meant to make code more portable.
This type is described in the header file stddef. h for C and in the file cstddef for C++. Types defined by the header file stddef. h are located in the global namespace while cstddef places the size_t type in the namespace std.
Yes, size_t is guaranteed to be an unsigned type.
size_t is commonly used for array indexing and loop counting. Programs that use other types, such as unsigned int, for array indexing may fail on, e.g. 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic.
Your alias will not cause any issue. It appears in its own namespaces scope, so the alias declaration isn't going to re-declare anything. And even if client code is going to be irresponsible and do something naughty like:
using namespace std;
using namespace N;
size_t foo;
That is still fine, since size_t
is the same type, regardless of which namespace the alias came from. Name lookup fails only if the same name from different namespaces refers to different entities:
[namespace.udir]
6 If name lookup finds a declaration for a name in two different namespaces, and the declarations do not declare the same entity and do not declare functions, the use of the name is ill-formed.
An "entity" according to the C++ standard covers a broad range of things, including types. And that is the sticking point, because a type alias is not a type, it's only a new name for an already existing type. So the two (unqualified) aliases name the same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With