代码之家  ›  专栏  ›  技术社区  ›  gct

使用带有部分类专门化的crtp?

  •  3
  • gct  · 技术社区  · 7 年前

    我试着加入一个 operator [] 和一个班。我的问题是我已经对类进行了部分专门化,编译器不喜欢我不为派生类指定模板参数:

    #include <iostream>
    #include <type_traits>
    
    using namespace std;
    
    template <typename T>
    struct mixin {
        template <typename U>
        void operator[](U u) {
            cout << u;
        }
    };
    
    
    template <typename T, typename = void>
    struct derived : mixin<derived> {};
    
    
    template <typename T>
    struct derived<T, 
        typename enable_if<
            is_same<T, int>{}
        >::type> : mixin<derived> {};
    
    
    int main() {
        derived<int> d;
        d[3.14];
    }
    

    随着叮当声这给:

    test.cc:16:24: error: use of class template 'derived' requires template arguments
    struct derived : mixin<derived> {};
                           ^~~~~~~
    test.cc:16:8: note: template is declared here
    struct derived : mixin<derived> {};
           ^
    test.cc:23:22: error: use of class template 'derived' requires template arguments
        >::type> : mixin<derived> {};
                         ^~~~~~~
    test.cc:16:8: note: template is declared here
    struct derived : mixin<derived> {};
           ^
    

    GCC的帮助更是微乎其微:

    test.cc:16:31: error: type/value mismatch at argument 1 in template parameter list for ‘template<class T> struct mixin’
     struct derived : mixin<derived> {};
                                   ^
    test.cc:16:31: note:   expected a type, got ‘derived’
    test.cc:23:29: error: type/value mismatch at argument 1 in template parameter list for ‘template<class T> struct mixin’
         >::type> : mixin<derived> {};
                                 ^
    test.cc:23:29: note:   expected a type, got ‘derived’
    test.cc: In function ‘int main()’:
    

    是在mixin子句中重新指定模板参数的唯一选项吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   einpoklum    7 年前

    好吧,试试这个:

    #include <iostream>
    #include <type_traits>
    
    using namespace std;
    
    template <typename T>
    struct mixin {
        template <typename U>
        void operator[](U u) {
            cout << u;
        }
    };
    
    
    template <typename T, typename = void>
    struct derived : mixin<derived<T>> {};
    
    
    template <typename T>
    struct derived<T,
        typename enable_if<
            is_same<T, int>::value
        >::type> : mixin<derived<T>> {};
    
    
    int main() {
        derived<int> d;
        d[3.14];
    }
    

    是的 work

    我改变了什么:

    1. 使用 is_same<foo,bar>::value 不是 is_same<foo,bar>{} 编辑: 嗯,看来你根本不需要改变。整洁!
    2. 在使用 mixin<derived> . 你一直在 方式 太乐观了…
    推荐文章