Constexpr counter that works on GCC 8, and is not restricted to namespace scope

后端 未结 2 862
臣服心动
臣服心动 2021-01-05 09:50

I\'m trying to learn some arcane stateful template metaprogramming tricks.
(Here\'s why I want to learn it. Unfortunately this library doesn\'t work on GCC

2条回答
  •  余生分开走
    2021-01-05 10:32

    The body of a constexpr function template must yield the same answer for all instatiations with the same template parameters and same arguments. You need to add a level of indirection, so the calculation can happen in the default argument of a template parameter dependent on the first.

    See https://gcc.godbolt.org/z/GHfKKf

    namespace Meta
    {
        template  struct Tag {};
    
        template
        struct Checker{
            static constexpr int currentval() noexcept{
                return N;
            }
        };
    
        template
        struct CheckerWrapper{
            template>::Read(),int M=Checker::currentval()>
            static constexpr int currentval(){
                return M;
            }
        };
    
        template
        struct Checker{
            template::currentval()>
            static constexpr int currentval() noexcept{
                return M;
            }
        };
    
        template>::ReadSet()>
        struct Next{
            static constexpr int value() noexcept{
                return N;
            }
        };
    
        template  class TaggedCounter
        {
          public:
            template ::currentval()> static constexpr int Value(){
                return Next::value();
            }
        };
    }
    

提交回复
热议问题