C++11变分模板
C++11 Variadic Template
本文关键字:C++11 更新时间:2023-10-16
我从这里得到了一些制作c++可变模板的示例代码:
http://en.wikipedia.org/wiki/Variadic_template
我的代码如下。
#ifdef DEBUG
#define logDebug(x, ...) streamPrintf( x, ##__VA_ARGS__ );
#else
#define logDebug(x, ...)
#endif
void streamPrintf(const char *s);
template<typename T, typename... Args>
void streamPrintf(const char *s, T value, Args... args)
{
while (*s) {
if (*s == '%') {
if (*(s + 1) == '%') {
++s;
}
else {
std::cout << value;
streamPrintf(s + 1, args...);
return;
}
}
std::cout << *s++;
}
throw std::logic_error("extra arguments provided to printf");
}
void streamPrintf(const char *s)
{
while (*s) {
if (*s == '%') {
if (*(s + 1) == '%') {
++s;
}
else {
throw std::runtime_error("invalid format string: missing arguments");
}
}
std::cout << *s++;
}
}
但它只打印垃圾。使用这个的主要原因是我可以打印出std::string。如何打印出正确的值?
我这样调用函数:
logDebug("Event is, event=%", value);
Peter T通过聊天发现了这个问题。它不能正确打印uint8_t,因为它将其视为ASCII。它需要类型转换为例如uint16_t。当我有解决方案时,我会把它张贴在这里。
在printf中使用可变模板的一个好例子可以在这里找到:
http://msdn.microsoft.com/en-us/library/dn439779.aspx
void print() {
cout << endl;
}
template <typename T> void print(const T& t) {
cout << t << endl;
}
template <typename First, typename... Rest> void print(const First& first, const Rest&... rest) {
cout << first << ", ";
print(rest...); // recursive call using pack expansion syntax
}
int main()
{
print(); // calls first overload, outputting only a newline
print(1); // calls second overload
// these call the third overload, the variadic template,
// which uses recursion as needed.
print(10, 20);
print(100, 200, 300);
print("first", 2, "third", 3.14159);
}
相关文章:
- MSVC是否支持C++11样式的属性而不是__declspec
- 创建LinkedList退出,返回代码为-11(SIGSEGV)
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 如何将模板转换为C++11之前的模板
- c++11评估顺序(未定义的行为)
- C++中的VLA,扩展名为std=C++11
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- "类模板示例<int>;"语句对 C++11 是什么意思?
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- 如何使用lock_guard在c++11中实现scoped_lock功能
- C++11 中不同类型的对象的 std::array 的替代方案
- 为什么 -mmacosx-version-min=10.10 不阻止使用标记为从 10.11 开始的函数?
- 为什么我的C++代码中出现'Segmentation Fault: 11'行?
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- STLPort using C++11
- Qt 5.11.2 (Clang 8.0 (Apple), 64 位), 找不到 QJSEngine 文件
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- C++11 迭代向量的新方法?