c – 如何使用sfinae选择构造函数?
发布时间:2020-12-16 07:49:39 所属栏目:百科 来源:网络整理
导读:在模板元编程中,可以在返回类型上使用SFINAE来选择某个模板成员函数,即 templateint N struct A { int sum() const noexcept { return _sumN-1(); }private: int _data[N]; templateint I typename std::enable_if I,int::type _sum() const noexcept { retu
在模板元编程中,可以在返回类型上使用SFINAE来选择某个模板成员函数,即
template<int N> struct A { int sum() const noexcept { return _sum<N-1>(); } private: int _data[N]; template<int I> typename std::enable_if< I,int>::type _sum() const noexcept { return _sum<I-1>() + _data[I]; } template<int I> typename std::enable_if<!I,int>::type _sum() const noexcept { return _data[I]; } }; 但是,这对于构造函数不起作用.假设我想声明构造函数 template<int N> struct A { /* ... */ template<int otherN> explicit(A<otherN> const&); // only sensible if otherN >= N }; 但不允许其他N N. 那么,SFINAE可以在这里使用吗?我只对允许自动模板参数扣除的解决方案感兴趣,所以 A<4> a4{}; A<5> a5{}; A<6> a6{a4}; // doesn't compile A<3> a3{a5}; // compiles and automatically finds the correct constructor 注意:这是一个非常简单的例子,其中SFINAE可能是过度的,static_assert可能就足够了.但是,我想知道是否可以使用SFINAE. 解决方法
您可以在模板中添加一个默认的类型参数:
template <int otherN,typename = typename std::enable_if<otherN >= N>::type> explicit A(A<otherN> const &); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |