簡體   English   中英

enable_if有條件地包含成員函數

[英]enable_if to conditionally include member functions

我有一個模板類,其類型是迭代器。 我想根據模板參數的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告訴我(粗略地): error: no type named 'type' in 'std::__1::enable_if<false, MyTemplateParameter>'; 'enable_if' cannot be used to disable this declaration error: no type named 'type' in 'std::__1::enable_if<false, MyTemplateParameter>'; 'enable_if' cannot be used to disable this declaration

有沒有辦法完成我正在嘗試的東西?

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

    #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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM