lundi 10 janvier 2022

SFINAE for constructors [duplicate]

Before closing this as a duplicate (since there are several questions like this which did actually explain how to achieve the solution - this, and this), I did go through the similar questions, but after doing the same I still get hit by the 'enable_if' cannot be used to disable this declaration. So here is my example:

#include <iostream>
#include <memory>
#include <type_traits>

namespace std
{
    
template<typename>
struct is_shared_ptr : std::false_type {};

template<typename T>
struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};

}

template<typename T>
struct Foo
{
    template<typename ... Arguments>
    Foo(Arguments&& ... arguments, std::enable_if_t<!std::is_shared_ptr<T>::value>* = nullptr)
    {
        std::cout << "ctor without shared_ptr\n";
    }
    
    template<typename ... Arguments>
    Foo(Arguments&& ... arguments, std::enable_if_t<std::is_shared_ptr<T>::value>* = nullptr)
    {
        std::cout << "ctor with shared_ptr\n";
    }

    T value_;
};

int main(int argc, char **argv)
{
    Foo<int> a;
    Foo<std::shared_ptr<int>> b;
    return 0;
}

Here is the link to this example on coliru. What I want to achieve is being able to initialise value_ with make shared when T is std::shared_ptr. The other questions show that moving the std::enable_if deduction to function parameters work, but not in my case. Am I missing/overlooked something in the examples?

Aucun commentaire:

Enregistrer un commentaire