我有这个示例代码块:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string blank = " ";
cout << "Hello" << blank << "47";
}
Run Code Online (Sandbox Code Playgroud)
我的原始代码中有很多此类型的cout.我希望能够将空白字符串更改为setw(2)函数,而无需在我的代码中的每个cout上用setw(2)替换空白.那么有没有办法将cpp函数设置为变量?所以我可以通过输入名称来调用该函数?例如:
func blank = setw(2);
cout<< "Hello" << blank << "47";
Run Code Online (Sandbox Code Playgroud)
该类型std::setw(x)是不确定的,但你并不需要知道这一点.
你可以使用auto:
auto blank = std::setw(2);
Run Code Online (Sandbox Code Playgroud)
正如@StoryTeller指出的那样,虽然这应该适用于理智的实现,但并不能保证.
更安全的选择是使类重载<<:
struct blank_t {} blank;
std::ostream &operator<<(std::ostream &s, blank_t)
{
return s << std::setw(2);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
663 次 |
| 最近记录: |