Can defining size_t in my own namespace create ambiguity or other bugs?
Asked Answered
X

1

5

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

Xe answered 11/4, 2019 at 7:25 Comment(0)
C
6

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.

Comment answered 11/4, 2019 at 7:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.