结合函数参数包和默认参数 [英] Combining function parameter pack and default arguments
问题描述
我有一个带参数包的函数:
I have a function with a parameter pack:
template<typename... Targs>
void tprintf(const char* format, Targs... args) {}
(实现无关紧要,只是签名).我想使用 GCC/Clang 内置函数将源位置添加为默认参数.类似的东西
(the implementation shouldn't matter, just the signature). I want to add source position as default argument, using the GCC/Clang builtins. Something like
template<typename... Targs>
void tprintf(const char* format, Targs... args,
const char* file = __builtin_FILE(),
unsigned line = __builtin_LINE()) {}
这可以编译,但调用它并没有像我希望的那样将参数传递给 args
;例如
This compiles, but calls to it are not passing parameters to args
as I hoped; e.g.
tprintf("%d%s", 0, "a");
给出(在 Clang 10 上)
gives (on Clang 10)
<source>:7:5: error: no matching function for call to 'tprintf'
tprintf("%d%s", 0, "a");
^~~~~~~
<source>:2:6: note: candidate function template not viable: no known conversion from 'const char [2]' to 'unsigned int' for 3rd argument
void tprintf(const char* format, Targs... args,
^
这似乎表明 args
是空的,0
是 file
,而 "a"
是 行代码>.
which seems to indicate args
is empty, 0
is file
, and "a"
is line
.
实际上,在编写问题时,我发现显式传递 Targs
有效:
Actually, while writing the question I've found that explicitly passing Targs
works:
tprintf<int, char*>("%d%s", 0, "a");
是否可以避免这种情况?
Is it possible to avoid this?
推荐答案
解决方案是给我们 C++20 的 std::source_location
:
The solution would be to us C++20's std::source_location
:
#include <iostream>
#include <source_location>
template<typename... Targs, auto location = source_location::current()>
auto tprintf(char const* format, Targs const&... args) -> void {
std::cout
<< std::format("{}:{}: ", location.file_name(), location.line())
<< std::format(format, args...);
}
auto main() -> int {
tprintf("hello {}", "world"); // prints "example.cpp:12: hello world"
}
如果 C++20 不是一个选项(尤其是在当前,编译器不支持源位置),那么有一种方法可以不用宏来实现.您可以简单地对编译器内置程序进行一些间接操作.
If C++20 is not an option (especially at this current time, compilers don't support source location) then there is a way to do it without macros. You can simply do a little indirection over the compiler built-ins.
不能将默认参数放在可变参数之后,但可以将它们放在第一个参数的构造函数中以达到相同的效果:
You cannot put defaulted arguments after the variadic arguments, but you can put them in the constructor of the first parameter to have the same effect:
#include <cstdio>
struct location_and_format {
constexpr location_and_format(
char const* _format,
char const* _file_name = __builtin_FILE(),
unsigned _line = __builtin_LINE()
) noexcept : format{_format}, file_name{_file_name}, line{_line} {}
char const* format;
char const* file_name;
unsigned line;
};
template<typename... Targs>
void tprintf(location_and_format format, Targs... args) {
printf("%s:%u: ", format.file_name, format.line);
printf(format.format, args...);
}
int main() {
tprintf("hello %s", "world"); // prints example.cpp:22: hello world
}
这篇关于结合函数参数包和默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!