incomprehensible с++ compiler behavior

Viewed 99

Maybe I don't know something about C++, but I found incomprehensible (and dangerous in my opinion) C++ compiler behavior.

MSVC, g++ and Clang behave the same.

Q: Why function ::a::f is visible as f inside b::f(bool)?

namespace a {

struct C {
    bool value;
    C(): value(false) {}
    C(C const &): value(false) {}
    explicit C(bool value): value(value) {}
};

inline C f(bool value) { return C(value); }

// why this function is visible as `f` inside `b::f(bool)`?
inline C f(C const &value) { return C(not value.value); }

}

namespace b {

inline bool f(::a::C const &value) { return value.value; }

inline bool f(bool value) {
#ifdef WORK_AROUND_PROBLEM
    return b::f(a::f(value));
#else
    // why `::a::f` is visible as `f` here?
    return f(a::f(value)).value;
#endif
}

}


int main(int, char **) {
    if (b::f(false) or (! b::f(true))) return 1;
    if (b::f(0)) return 2;
    if (b::f(a::C(false)) || (! b::f(a::C(true)))) return 3;
    return 0;
}

======== UPDATE ========

First code example can be explained with Argument dependent lookup https://en.cppreference.com/w/cpp/language/adl. Thanks for the answers. =)

But it's still not clear to me how to properly deal with set of "universal functions". In context of first example I cannot figure out how to properly replace f (C const &) with template <class ... T> auto f (T && ...)

As next example [c++20], I've posted a piece of more real code (but simplified) here. This is a part of header-only library. Here I would like to have a universal make function for the ::exception::Walker. And a universal make function for exception::Backtrace. Moreover, I would like to have minimal connectivity between ::exception::walker and ::exception::backtrace namespaces. See comments in the code below.

#include <cstdint>

#include <list>
#include <ranges>
#include <utility>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <exception>
#include <stdexcept>
#include <type_traits>


// from <.../exception/walker.fwd.hpp>
namespace exception {
namespace walker {

struct Class;
struct Iterator;

using Value = ::std::exception_ptr;

template <class ... T> auto make(T && ...);

} // namespace walker

using Walker = walker::Class;

} // namespace exception


// from <.../exception/backtrace.fwd.hpp>
namespace exception {
namespace backtrace {

using Item = ::std::exception_ptr;
using Class = ::std::vector<Item>;

auto make();
template <class T> auto make(T &&source);
template <class beginT, class endT> auto make(beginT &&begin, endT &&end);

} // namespace backtrace

using BackTrace = backtrace::Class;

} // namespace exception


// from <.../exception/walker.hpp>
namespace exception::walker {

struct Class final {
    using Value = walker::Value;
    using Iterator = walker::Iterator;

    auto begin() const noexcept(true);
    auto end() const noexcept(true);

    Class() noexcept(true) = default;
    Class(Class &&) noexcept(true) = default;
    Class(Class const &) noexcept(true) = default;

    template <class headT, class ... tailT> requires((0 < sizeof ... (tailT)) or (not ::std::is_base_of_v<Class, ::std::decay_t<headT>>))
    explicit Class(headT &&head, tailT && ... tail) noexcept(true);

private:
    Value last_;

    // There was a lot of overloads
    template <class T> decltype(auto) make_value_(T &&value) noexcept(true);
};

struct Iterator final {
    using iterator_category = ::std::input_iterator_tag;
    using difference_type = ::std::ptrdiff_t;
    using value_type = Value;
    using pointer = Value *;
    using reference = Value &;

    inline auto & operator*() const noexcept(true) { return value_; }
    inline auto * operator->() const noexcept(true) { return &value_; }

    inline auto & operator++() noexcept(true) {
        auto const temporary_ = value_;
        if (static_cast<bool>(temporary_)) {
            value_ = {};
            try { ::std::rethrow_exception(temporary_); }
            catch(::std::exception const &exception_) {
                try { ::std::rethrow_if_nested(exception_); }
                catch (...) { value_ = ::std::current_exception(); }
            }
            catch (...) {}
        }
        return *this;
    }

    inline auto operator++(int) noexcept(true) { auto const temporary_ = *this; ++(*this); return temporary_; }

    inline auto operator==(Iterator const &other) const noexcept(true) { return value_ == other.value_; };
    inline auto operator!=(Iterator const &other) const noexcept(true) { return not (*this == other); };

    Iterator & operator=(Iterator &&) noexcept(true) = default;
    Iterator & operator=(Iterator const &) noexcept(true) = default;

    Iterator() noexcept(true) = default;
    Iterator(Iterator &&) noexcept(true) = default;
    Iterator(Iterator const &) noexcept(true) = default;

    inline explicit Iterator(Value const &value) noexcept(true): value_{value} {}

private:
    value_type value_;
};

inline auto Class::begin() const noexcept(true) { return Iterator{last_}; }
inline auto Class::end() const noexcept(true) { return Iterator{}; }

template <class T> inline decltype(auto) Class::make_value_(T &&value) noexcept(true) {
    if constexpr (::std::is_same_v<::std::exception_ptr, ::std::decay_t<decltype(value)>>) return ::std::forward<decltype(value)>(value);
    else return ::std::make_exception_ptr(::std::forward<decltype(value)>(value));
}

template <class headT, class ... tailT> requires((0 < sizeof ... (tailT)) or (not ::std::is_base_of_v<Class, ::std::decay_t<headT>>))
inline Class::Class(headT &&head, tailT && ... tail) noexcept(true): last_{::exception::walker::Class::make_value_(::std::forward<headT>(head), ::std::forward<tailT>(tail) ...)} {}

template <class ... T> inline auto make(T && ... payload) { return Class{::std::forward<T>(payload) ...}; }

} // namespace exception::walker


// from <.../exception/backtrace.hpp>
namespace exception::backtrace {
namespace private_ {

// in fact, it would be more correct to use const lvalue to T (T const &source) instead universal reference (T &&), but then
// ::other::namespace::make function may be used (::exception::walker::make for example if ::std::decay_t<sourceT> will be ::exception::walker::Class)
template <class sourceT> inline auto make(void const *, sourceT const &source) {
    using CollectorItem = ::std::decay_t<decltype(*::std::begin(source))>;
    auto collector_ = ::std::list<CollectorItem>{};
    auto size_ = static_cast<::std::size_t>(0);
    for (auto const &exception_ : source) { size_++; collector_.push_front(exception_); }
    auto result_ = Class(size_);
    ::std::copy(collector_.begin(), collector_.end(), result_.begin());
    return result_;
}

template <class T> inline auto make(::std::exception const *, T &&exception) {
    // sad, but without knowledge about content of namespace in which the real type of T is located, I have to write here explicitly ::exception::backtrace::private_::make
    return ::exception::backtrace::private_::make(static_cast<void const *>(nullptr), ::exception::walker::make(::std::forward<T>(exception)));
}

template <class T> inline auto make(::std::exception_ptr const *, T &&exception) {
    // sad, without knowledge about content of namespace in which the real type of T is located, I have to write here explicitly ::exception::backtrace::private_::make
    return ::exception::backtrace::private_::make(static_cast<void const *>(nullptr), ::exception::walker::make(::std::forward<T>(exception)));
}

} // namespace private_

template <class T> inline auto make(T &&source) {
    // sad, but without knowledge about content of namespace in which the real type of T is located, I have to write here explicitly ::exception::backtrace::private_::make
    return ::exception::backtrace::private_::make(static_cast<::std::decay_t<T> const *>(nullptr), ::std::forward<T>(source));
}

template <class beginT, class endT> inline auto make(beginT &&begin, endT &&end) {
    // sad, but without knowledge about content of namespace in which the real type of ::std::ranges::subrange result is located, I have to write here explicitly ::exception::backtrace::make
    return ::exception::backtrace::make(::std::ranges::subrange(::std::forward<beginT>(begin), ::std::forward<endT>(end)));
}

} // namespace exception::backtrace


namespace test_ {
    inline static auto internal() { throw ::std::runtime_error{"internal function error"}; }
    inline static auto external() {
        try { internal(); }
        catch(...) { ::std::throw_with_nested(::std::runtime_error{"external function error"}); }
    }
}


int main(int, char **) {
    try { test_::external(); }
    catch(...) {
        for (auto const &exception_: ::exception::backtrace::make(::std::current_exception())) {
            try { ::std::rethrow_exception(exception_); }
            catch(::std::exception const &exception_) { ::std::clog << exception_.what() << ::std::endl << ::std::flush; }
            catch(...) { ::std::clog << "unknown exception" << ::std::endl << ::std::flush; }
        }
    }

    return 0;
}
1 Answers

This is due to Argument dependent lookup.

If a function takes a parameter of a custom type, the namespace that the type is declared in is searched for viable overloads when calling a function.

f(a::f(value))

Is passing a C to f. This triggers ADL, thus additionally to doing name lookup in the surounding scopes, the compiler also searches in namespace a since C is declared there.

This is most commonly an important feature when defining free-function operator overloads. We can put them in the same namespace as the type in question, and ADL will make sure the overload is found at name-lookup without polluting the global/outer scopes.

Related