加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用SFINAE“重载”构造函数

发布时间:2020-12-16 09:58:25 所属栏目:百科 来源:网络整理
导读:为什么以下 attempt重载构造函数Foo :: Foo失败?此外,我很欣赏替代方案/解决方法 #include vector#include type_traitsnamespace xyz{ struct MemoryManager{}; templatetypename T,typename Alloc=MemoryManager class vector { };}templatetypename T,tem
为什么以下 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>,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,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 */ }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读