(Partially) specializing a non-type template parameter of dependent type

前端 未结 4 1899
难免孤独
难免孤独 2020-12-01 04:06

Maybe I\'m tired, but I\'m stuck with this simple partial specialization, which doesn\'t work because non-type template argument specializes a template parameter with

4条回答
  •  無奈伤痛
    2020-12-01 04:19

    You need to pass an integral value in a template, Both, your first and second template, will not work if the type T is not an integral type.

    You can pass Traits as a typed template parameter to specify the value N:

    #include 
    
    // error: ‘double’ is not a valid type for a template non-type parameter
    template  struct X0;
    
    // error: ‘double’ is not a valid type for a template non-type parameter
    template  struct X1;
    
    
    
    template 
    struct IntegralTraits {
        static constexpr T Value() { return N; }
    };
    
    template 
    struct X2 {
        static constexpr T Value() { return Traits::Value(); }
    };
    
    template 
    struct X2 {
        static constexpr T Value() { return T(); }
    };
    
    
    int main() {
        // error: ‘double’ is not a valid type for a template non-type parameter
        // X0();
    
        // error: ‘double’ is not a valid type for a template non-type parameter
        // X1();
    
        X2 a;
        X2> b;
    
        std::cout.precision(2);
        std::cout << std::fixed  <<  a.Value() << ", "<< b.Value() << '\n';
        return 0;
    }
    

    If you limit yourself to integral types pick a large one:

    template  struct X {};
    

提交回复
热议问题