Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to function is ambiguous when irrelevant type defined as alias

After reading of a great article True Story: Efficient Packing I tried to implement tuple by myself as exercise:

#include <type_traits>
#include <utility>
#include <functional>

template< std::size_t I, typename T >
struct tuple_leaf { T value; };

template< std::size_t I, typename T >
T & get(tuple_leaf< I, T > & leaf)
{ return leaf.value; }

template< typename Is, typename ...Ts >
struct tuple_base;

template< std::size_t ...Is, typename ...Ts >
struct tuple_base< std::index_sequence< Is... >, Ts... >
    : tuple_leaf< Is, Ts >...
{
    using tuple_base_t = tuple_base;
    template< typename ...Args, typename = std::enable_if_t< (sizeof...(Ts) == sizeof...(Args)) > >
    tuple_base(Args &&... args)
        : tuple_leaf< Is, Ts >{std::forward< Args >(args)}...
    { ; }
};

#if 0
template< typename ...Ts >
struct tuple
    : tuple_base< std::index_sequence_for< Ts... >, Ts... >
{
    using tuple_base_t = typename tuple::tuple_base_t;
    using tuple_base_t::tuple_base_t;
    using tuple_base_t::operator = ;
};
#else
// terse
template< typename ...Ts >
using tuple = tuple_base< std::index_sequence_for< Ts... >, Ts... >;
#endif

template< typename ...Args >
tuple< Args &&... >
forward_as_tuple(Args &&... args)
{ return {std::forward< Args >(args)...}; }

#include <tuple>

int
main()
{
    tuple< int > t(1);
    auto f = forward_as_tuple(t);
    (void)f;
    return 0;
}

Live example

After implementation of forward_as_tuple I decide to change definition of tuple type from class template to alias template of its base class template, because all I need from splitting into class tuple itself and its implementation class tuple_base is just std::index_sequence_for for variadic template type parameters pack — alias template is exactly suitable tool for this purpose. After doing that I get an error (#if 0 case):

error: call to 'forward_as_tuple' is ambiguous

It looks strange for me, because alias template does nothing and on the other hand forward_as_tuple called for type from the same namespace - I was hoping that ADL should work for the case above for sure.

How to explain the difference between #if 1 and #if 0 versions of code?

like image 383
Tomilov Anatoliy Avatar asked Oct 18 '22 15:10

Tomilov Anatoliy


1 Answers

Adl causes lookup in the type passed, and the template arguments of the type passed.

The tuple non-alias has its types and itself as places to look for ADL.

The tuple alias case has a std::index_sequence in its template argument list. This causes std::forward_as_tuple to be considered, in addition to your forward_as_tuple. They are equally good matches, and ambiguity occurs.

As @Piotr noted above in comments, tuple<std::string> exhibits this problem even in the non-alias case.

like image 117
Yakk - Adam Nevraumont Avatar answered Nov 12 '22 21:11

Yakk - Adam Nevraumont