"Overloading" SFINAE 构造函数

"Overloading" constructors with SFINAE

为什么以下 attempt 在重载构造函数 Foo::Foo 时会失败?另外,我很感激 alternatives/workarounds

#include <vector>
#include <type_traits>

namespace xyz
{   
    struct MemoryManager{};

    template<typename T , typename Alloc=MemoryManager>
    class vector
    {
    };
}


template<typename T, template<typename,typename> class V , typename A>
struct Foo
{
    template<typename U = T ,
             typename Dummy = typename std::enable_if<
                 std::is_same<std::vector<U>, V<U,A> >::value >::type >
    Foo() // when instantiated with the std vector
    {
    }

    template<typename U = T ,
             typename Dummy = typename std::enable_if<
                 std::is_same<xyz::vector<U>, V<U,A> >::value >::type >
    Foo() // when instantiated with my custom vector
    {
    }   
};

int main()
{
}

错误信息:

23:3: error: ‘template<class T, template<class, class> class V, class A> template<class U, class Dummy> Foo<T, V, A>::Foo()’ cannot be overloaded
   Foo() // when instantiated with my custom vector

18:3: error: with ‘template<class T, template<class, class> class V, class A> template<class U, class Dummy> Foo<T, V, A>::Foo()’
   Foo() // when instantiated with the std vector

您不能以这种方式重载构造函数,因为默认参数不是签名的一部分。实际上,您有:

template <typename, typename>
Foo();

template <typename, typename>
Foo();

这条规则在模板世界之外可能更清楚,因为这两个函数不能相互重载:

void foo(int x = 42);
void foo(int y = 17);

您可以将第二个模板参数设置为默认的 非类型 参数,以便两个构造函数具有不同的签名:

template<typename U = T , 
         std::enable_if_t<std::is_same<std::vector<U> , V<T,A> >::value, int> = 0>
Foo() // when instantiated with the std vector

或者您可以使用虚拟类型委托两个构造函数:

template <typename T> struct tag { };

Foo()
: Foo(tag<V<T,A>>{})
{ }

Foo(tag<std::vector<T>> )
{ /* std vector */ }

Foo(tag<xyz::vector<T>> )
{ /* your vector */ }