Types of Conditional and Design Arguments SFINAE

I came across the following method, which allows you to build a wrapper around T, but from objects of the type U, if it Tis constructive from U:

template< typename T >
struct S {
    template< typename U,
              typename = std::enable_if_t<
                  std::is_constructible< T, U >::value > >
    explicit S (U&& arg) : value (arg)
        { }
    ...
};

IIUC, the type Uused in the test is_constructible, may differ from the cv-qualified type arg.
Is it possible that the SFINAE test might fail, although the expression is value(arg)valid?

+4
source share
1 answer

Is it possible that the SFINAE test might fail, although the value of the expression (arg) is valid?

S: , .
() :

#include<type_traits>

template< typename T >
struct S {
    template< typename U
              , typename = std::enable_if_t<std::is_constructible< T, U >::value >
    > explicit S (U&& arg) : value{arg} {}

    T value;
};

struct A {};
struct B {
    B(A &) {}
};

int main() {
    S<B> s(A{});
}

, , :

, typename = std::enable_if_t<std::is_constructible< T, U >::value >

, . lvalue rvalue A ( arg) value.
B rvalue A, sfinae (), ​​ , sfinae, .
, B lvalue A, , , value{arg}.


S :

#include<utility>

// ...

template< typename T >
struct S {
    template< typename U
              , typename = std::enable_if_t<std::is_constructible< T, U >::value >
    > explicit S (U&& arg) : value (std::forward<U>(arg)) { }

    T value;
};

std::forward .
, , , , .

+4

Source: https://habr.com/ru/post/1653894/


All Articles