本文介绍了简化std :: string构造,包括在C ++中连接整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找以下更优雅的快捷方式:

Looking for a more elegant shortcut to the following:

for (int i=1; i<=maxNum; i++)
{
   std::ostringstream s;
   s << i;
   std::string group1 = "group1_" + s.str();
   std::string group2 = "group2_" + s.str();
   .
   .
   .

   val = conf->read(group1.c_str());
   .
   .
   .
}

任何人都可以想到一种优雅的方式:

Can anyone think of an elegant way like:

conf->read({SOMEMACRO or function}("group1_", i));

这可以用内置的C ++工具来完成吗?

Can this be done in place with a built-in C++ facility? Btw, boost is not an option.

推荐答案

/ p>

I think I'd use a (somewhat restricted) copy of Boost's lexical_cast:

template <class T, class U>
T lexical_cast(U const &input) {
     std::stringstream buffer;
     buffer << input;

     T ret;
     buffer >> ret;
     return ret;
}

for (int i=0; i<maxNum; i++)
    val = conf->read("group1_" + lexical_cast<std::string>(i));

这篇关于简化std :: string构造,包括在C ++中连接整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:14