代码之家  ›  专栏  ›  技术社区  ›  Yippie-Ki-Yay

C++模板特化

  •  3
  • Yippie-Ki-Yay  · 技术社区  · 15 年前

    (此代码导致编译时间错误)。

    E、 g,我只想在派生类中添加特定的模板专门化。

    struct Base {
       template <typename T> void Method(T a) {
          T b;
       }
    
       template <> void Method<int>(int a) {
          float c;
       }
    };
    
    struct Derived : public Base {
       template <> void Method<float>(float a) {
          float x;
       }
    };
    
    1 回复  |  直到 15 年前
        1
  •  7
  •   Johannes Schaub - litb    15 年前

    超载怎么样

    struct Base {
       template <typename T> void Method(T a) {
          T b;
       }
    
       void Method(int a) {
          float c;
       }
    };
    
    struct Derived : public Base {
       using Base::Method;
       void Method(float a) {
          float x;
       }
    };
    

    struct Base {
       template <typename T> void Method(T a) {
          T b;
       }
    };
    
    template <> void Base::Method<int>(int a) {
       float c;
    }
    

    所有显式专门化都需要给出要专门化的模板的名称,或者与模板在同一范围内。不能只在这样的派生类中编写显式专门化。