C++ Logo

std-proposals

Advanced search

Automatic export literals operators into global scope when the header is included

From: kang hewill <hewillk_at_[hidden]>
Date: Thu, 11 Mar 2021 16:14:22 +0800
Dear Experts:

When C++14 introduces literals operators, we can conveniently use auto s =
"hello"s; to define an std::string, but before that, we must type using
std::string_literals::operator""s;.
This is very unfriendly for users who just want to save typing but often
need to define a simple std::string on different files (or for AAA-style
enthusiasts). It would be great if these literals operators can be
automatically introduced into the global scope when their corresponding
headers are included.

One of the approaches would be put using
std::literals::xxx_literals::operator""xxx; directly in their headers
content:

#include <string> // using declaration already in it.#include <chrono>
// using declaration already in it.int main() {
  auto str = "hello world"s; // works!
  auto sec = 10s; // works!
}

I know this must be opposed by many people, but here the reasons:

*1.* The standard operators do not conflict with each other since they are
in different namespaces, even with the same name operator""s. since their
signatures are different.

*2. *These operators will not conflict with user-define operators which
must begin with _.

*3. *We are *not* put using namespace std::literals::xxx_literals; in
header, we just declare using std::literals::xxx_literals::operator""xxx.
So the other stuff on the same namespace is not polluting the global scope
even though there are only literals operators in those namespaces which are
we usually want.

*4. *If the standard introduces a new library along with literals
operators with
the same signature and the same name in the future, this will occur an
ambiguity:

#include <string>#include <network>int main() {
  auto s = "140.113.203.189"s; // string or socket?
}

but in this case, we better choose a different name for socket literals
like operator""sk. Since even those two literals operators in different
namespaces, we still can use them on the same scope at the same time:

#include <string> #include <network>int main() {
  using std::string_literals::operator""s;
  auto str = "140.113.203.189"s;
  using std::network_literals::operator""s;
  auto soc = "140.113.203.189"s; // ambiguous,
string_literals::operator""s still visible
}

Any comments? Are there other flaws that I haven't noticed? Or are
there other better solutions? Very appreciate your reply.

Sincerely
Hewill Kang

Received on 2021-03-11 02:14:37