gpt4 book ai didi

c++ - "Overloading"带有 SFINAE 的构造函数

转载 作者:太空狗 更新时间:2023-10-29 20:11:49 26 4
gpt4 key购买 nike

为什么会出现以下 attempt重载构造函数 Foo::Foo 失败?另外,我会很感激替代方案/解决方法

#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

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

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 */ }

关于c++ - "Overloading"带有 SFINAE 的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31138449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com