How to use source_location in a variadic template function?

后端 未结 4 914
悲哀的现实
悲哀的现实 2020-12-04 18:07

The C++20 feature std::source_location is used to capture information about the context in which a function is called. When I try to use it with a variadic tem

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 18:24

    template 
    void debug(Args&&... args,
               const std::source_location& loc = std::source_location::current());
    

    "works", but requires to specify template arguments as there are non deducible as there are not last:

    debug(42);
    

    Demo

    Possible (not perfect) alternatives include:

    • use overloads with hard coded limit (old possible way to "handle" variadic):

      // 0 arguments
      void debug(const std::source_location& loc = std::source_location::current());
      
      // 1 argument
      template 
      void debug(T0&& t0,
                 const std::source_location& loc = std::source_location::current());
      
      // 2 arguments
      template 
      void debug(T0&& t0, T1&& t1,
                 const std::source_location& loc = std::source_location::current());
      
      // ...
      

      Demo

    • to put source_location at first position, without default:

      template 
      void debug(const std::source_location& loc, Args&&... args);
      

      and

      debug(std::source_location::current(), 42);
      

      Demo

    • similarly to overloads, but just use tuple as group

      template 
      void debug(Tuple&& t,
                 const std::source_location& loc = std::source_location::current());
      

      or

      template 
      void debug(const std::tuple& t,
                 const std::source_location& loc = std::source_location::current());
      

      with usage

      debug(std::make_tuple(42));
      

      Demo

提交回复
热议问题