How to use source_location in a variadic template function?

后端 未结 4 913
悲哀的现实
悲哀的现实 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:21

    Just put your arguments in a tuple, no macro needed.

    #include 
    #include 
    
    template 
    void debug(
        std::tuple args,
        const std::source_location& loc = std::source_location::current())
    {
        std::cout 
            << "debug() called from source location "
            << loc.file_name() << ":" << loc.line()  << '\n';
    }
    

    And this works*.

    Technically you could just write:

    template 
    void debug(
        T arg, 
        const std::source_location& loc = std::source_location::current())
    {
        std::cout 
            << "debug() called from source location "
            << loc.file_name() << ":" << loc.line()  << '\n';
    }
    

    but then you'd probably have to jump through some hoops to get the argument types.


    * In the linked-to example, I'm using because that's what compilers accept right now. Also, I added some code for printing the argument tuple.

提交回复
热议问题