passing a static constexpr variable by universal reference?

前端 未结 1 692
难免孤独
难免孤独 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_<T> with a void default value, and write a typedef for A in terms of that

    template<class = void>
    struct A_
    {
        static constexpr size_t L = 4;
    
        template <typename T>
        void member_ref(T&& x) { cout << std::forward<T>(x) << endl; }
    
        template <typename T>
        void member_val(T x) { cout << x << endl; }
    
    };
    
    template<class T>
    constexpr size_t A_<T>::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<class P1, class P2, class P3 /* many more short parameter names */>
    constexpr SomeType A<P1, P2, P3, /* many more */>::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)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题