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

c – enable_if有条件地包含成员函数

发布时间:2020-12-16 03:28:31 所属栏目:百科 来源:网络整理
导读:我有一个模板类,其类型是迭代器.我想根据模板参数的iterator_category启用/禁用特定成员函数.特别是,如果模板参数是双向迭代器,我想启用operator.我的尝试是这样的: typename std::enable_if std::is_base_ofstd::bidirectional_iterator_tag,MyTemplatePar
我有一个模板类,其类型是迭代器.我想根据模板参数的iterator_category启用/禁用特定成员函数.特别是,如果模板参数是双向迭代器,我想启用operator.我的尝试是这样的:
typename std::enable_if<
       std::is_base_of<std::bidirectional_iterator_tag,MyTemplateParameter>::value,MyType&>::type
    operator --() {
    //do work
    return *this;
  }

Clang告诉我(粗略地):错误:’std :: __ 1 :: enable_if< false,MyTemplateParameter>‘中没有名为’type’的类型; ‘enable_if’不能用于禁用此声明

有没有办法完成我正在尝试的东西?

以下是某些上下文中的示例:

#include <iterator>
    #include <type_traits>

    template <typename TagType> 
    class test {
      public:
      typename std::enable_if<
         std::is_base_of<std::bidirectional_iterator_tag,TagType>::value,test>::type
      operator --() {
         return *this;
      }

    };

    int main(){

      test<std::random_access_iterator_tag> t1;
      test<std::forward_iterator_tag> t2;

    /*
    breakTemps.cpp:13:2: error: no type named 'type' in 'std::__1::enable_if<false,test<std::__1::forward_iterator_tag> >'; 'enable_if' cannot be used to disable this declaration
            std::is_base_of<std::bidirectional_iterator_tag,^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    breakTemps.cpp:25:35: note: in instantiation of template class 'test<std::__1::forward_iterator_tag>' requested here
       test<std::forward_iterator_tag> t2;
                                       ^
    */

}

解决方法

std :: enable_if需要依赖于成员模板本身的参数.
template <typename TagType>
class foo
{
public:
    template <typename U = TagType>
      typename std::enable_if<
         std::is_base_of<std::bidirectional_iterator_tag,U>::value,foo>::type
      operator --() {
         return *this;
      }
};

SFINAE将按预期工作.

int main() {
  foo<std::random_access_iterator_tag> f;
  foo<std::forward_iterator_tag> f2;
  --f; // fine
  --f2;
}

main.cpp:24:3: error: no match for 'operator--' (operand type is 'foo<std::forward_iterator_tag>')

--f2;

(编辑:李大同)

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

    推荐文章
      热点阅读