代码之家  ›  专栏  ›  技术社区  ›  Victor Liu

模板类模板模板构造器的C++显式模板特化

  •  5
  • Victor Liu  · 技术社区  · 15 年前

    template <class T>
    struct A{
        template <class U>
        A(U u);
    };
    

    我想为这样的声明写一个明确的专门化

    A<int>::A(float);
    

    在下面的测试代码中,如果我注释掉专门化,它将用g++编译。否则,它会说我的模板参数数目不对:

    #include <iostream>
    
    template <class T>
    struct A{
        template <class U>
        A(T t, U *u){
            *u += U(t);
        }
    };
    
    template <>
    template <>
    A<int>::A<int,float>(int t, float *u){
        *u += float(2*t);
    }
    
    int main(){
        float f = 0;
        int i = 1;
        A<int>(i, &f);
        std::cout << f << std::endl;
        return 0;
    }
    
    2 回复  |  直到 15 年前
        1
  •  4
  •   cpalmer    15 年前

    尝试

    template <>
    template <>
    A<int>::A(int t, float *u){
         *u += float(2*t);
    }
    

    这似乎对我有用。

        2
  •  1
  •   Potatoswatter    15 年前

    template <>
    template <>
    A<int>::A<float>(int t, float *u){
        *u += U(2*t);
    }