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

类模板中静态变量模板的部分特殊化

  •  4
  • Klaus  · 技术社区  · 6 年前

    如果我做了部分特化,我从clang和g++得到了不同的结果。

    template < typename T>
    class X
    {
        public:
            T i;
            X(T _i): i{_i}{}
    
            operator T(){ return i; }
    };  
    
    template < typename T2 >
    class Y
    {
        public:
            template <typename T>
                static X<T> x_in_y;
    };  
    
    template< typename T2> 
    template< typename T>
    X<T> Y<T2>::x_in_y{200};
    
    
    template<>
    template<>
    X<float> Y<int>::x_in_y<float>{100};
    
    template<>
    template<>
    X<int> Y<int>::x_in_y<int>{101};
    
    template<  >
    template< typename T >
    X<T> Y<bool>::x_in_y{77};
    
    
    
    int main()
    {
        std::cout << Y<int>::x_in_y<int> << std::endl;
        std::cout << Y<int>::x_in_y<float> << std::endl;
    
        std::cout << Y<float>::x_in_y<float> << std::endl;
        std::cout << Y<bool>::x_in_y<float> << std::endl;
    }
    

    我用g++和clang编译,得到了不同的行为:

    [~]$ g++ main.cpp 
    [~]$ a.out 
    101
    100
    200
    200
    
    [~]$ clang++ main.cpp 
    [~]$ a.out 
    101
    100
    200
    77
    

    奖励:有没有可能在其他方面进行专业化?:

    template< typename T2 >
    template<  >
    X<int> Y<T2>::x_in_y{105};
    
    0 回复  |  直到 6 年前