c++c++14language-lawyersfinaestdtuple

Making `std::get` play nice with SFINAE


std::get does not seem to be SFINAE-friendly, as shown by the following test case:

template <class T, class C>
auto foo(C &c) -> decltype(std::get<T>(c)) {
    return std::get<T>(c);
}

template <class>
void foo(...) { }

int main() {
    std::tuple<int> tuple{42};
    
    foo<int>(tuple);    // Works fine
    foo<double>(tuple); // Crashes and burns
}

See it live on Coliru

The goal is to divert the second call to foo towards the second overload. In practice, libstdc++ gives:

/usr/local/bin/../lib/gcc/x86_64-pc-linux-gnu/6.3.0/../../../../include/c++/6.3.0/tuple:1290:14: fatal error: no matching function for call to '__get_helper2'
    { return std::__get_helper2<_Tp>(__t); }
             ^~~~~~~~~~~~~~~~~~~~~~~

libc++ is more direct, with a straight static_assert detonation:

/usr/include/c++/v1/tuple:801:5: fatal error: static_assert failed "type not found in type list"
    static_assert ( value != -1, "type not found in type list" );
    ^               ~~~~~~~~~~~

I would really like not to implement onion layers checking whether C is an std::tuple specialization, and looking for T inside its parameters...

Is there a reason for std::get not to be SFINAE-friendly? Is there a better workaround than what is outlined above?

I've found something about std::tuple_size, but not std::get.


Solution

  • std::get<T> is explicitly not SFINAE-friendly, as per [tuple.elem]:

    template <class T, class... Types>
      constexpr T& get(tuple<Types...>& t) noexcept;
    // and the other like overloads
    

    Requires: The type T occurs exactly once in Types.... Otherwise, the program is ill-formed.

    std::get<I> is also explicitly not SFINAE-friendly.


    As far as the other questions:

    Is there a reason for std::get not to be SFINAE-friendly?

    Don't know. Typically, this isn't a point that needs to be SFINAE-ed on. So I guess it wasn't considered something that needed to be done. Hard errors are a lot easier to understand than scrolling through a bunch of non-viable candidate options. If you believe there to be compelling reason for std::get<T> to be SFINAE-friendly, you could submit an LWG issue about it.

    Is there a better workaround than what is outlined above?

    Sure. You could write your own SFINAE-friendly verison of get (please note, it uses C++17 fold expression):

    template <class T, class... Types,
        std::enable_if_t<(std::is_same<T, Types>::value + ...) == 1, int> = 0>
    constexpr T& my_get(tuple<Types...>& t) noexcept {
        return std::get<T>(t);
    }
    

    And then do with that as you wish.