6

タイプが反復子であるテンプレート化されたクラスがあります。テンプレート パラメーターの 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

私がしようとしていることを達成する方法はありますか?

いくつかのコンテキストでの例を次に示します。

    #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;
                                       ^
    */

}
4

1 に答える 1

11

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;
于 2014-02-05T07:05:35.040 に答える