passing a static constexpr variable by universal reference?

前端 未结 1 689
难免孤独
难免孤独 2021-01-18 23:16

In the following, static constexpr member L is initialized in-class A and then passed by value or by (universal) reference. The latter

1条回答
  •  伪装坚强ぢ
    2021-01-18 23:45

    You need to define A::L outside its class in a source file

    constexpr size_t A::L;
    

    Live example using Clang

    For header-only code, and if your class A is not already a template, you can define a class template A_ with a void default value, and write a typedef for A in terms of that

    template
    struct A_
    {
        static constexpr size_t L = 4;
    
        template 
        void member_ref(T&& x) { cout << std::forward(x) << endl; }
    
        template 
        void member_val(T x) { cout << x << endl; }
    
    };
    
    template
    constexpr size_t A_::L;
    
    using A = A_<>;
    

    Live Example.

    NOTE: this business can involve a fair amount of boiler-plate. It is good to note that one can write

    template
    <
        class MyConcept1, 
        class MyConcept2, 
        class YetAnotherConcept
        // more long and well-documented template parameter names
    >
    struct A
    {
        // many static constexpr variabels
    };
    
    template
    constexpr SomeType A::some_var;
    
    // many more one-liners.
    

    Template parameters just have formal names, they don't have to be the same everywhere (just put them in the right order everywhere, though!).

    0 讨论(0)
提交回复
热议问题