我想知道是否可以使用倍表达(以及如何写吧)在下面的例子。
#include <iostream>
#include <type_traits>
#include <typeinfo>
#include <sstream>
#include <iomanip>
template<int width>
std::string padFormat()
{
return "";
}
template<int width, typename T>
std::string padFormat(const T& t)
{
std::ostringstream oss;
oss << std::setw(width) << t;
return oss.str();
}
template<int width, typename T, typename ... Types>
std::string padFormat(const T& first, Types ... rest)
{
return (padFormat<width>(first + ... + rest)); //Fold expr here !!!
}
int main()
{
std::cout << padFormat<8>("one", 2, 3.0) << std::endl;
std::cout << padFormat<4>('a', "BBB", 9u, -8) << std::endl;
return 0;
}
我想到目前为止,但我并没有意识到这一点!
谢谢。
我猜你想调用padFormat
对每个参数,然后串联。因此,你必须写
return (padFormat<width>(first) + ... + padFormat<width>(rest));
(额外的括号是必需的;折叠表达式必须括在括号中是有效的。)