【问题标题】:How to emulate class template argument deduction pre-C++17?如何在 C++17 之前模拟类模板参数推导?
【发布时间】:2021-04-17 19:15:32
【问题描述】:

我正在努力从 C++ 代码库中删除 sscanf() 调用,并将其替换为此处描述的 std::stringstream 实现:https://www.quora.com/Is-there-a-C-alternative-to-sscanf。相关代码为:

template<class Char> 
class imatch 
{ 
    const Char* s; 
public: 
    imatch(const Char* x) :s(x) {} 
     
    template<class Stream> 
    friend Stream& operator >> (Stream& st, const imatch& m) 
    { 
        std::basic_string<Char> x; 
        st >> x; //strip spaces, read chars up to space 
        if(x!=m.s) st.setstate(st.failbit); //set as "failure" a mismatch 
        return st; 
    } 
}; 

然后在我的代码库中:

std::stringstream ss("value = 15"); //the input 
 
int val=0; 
ss >> imatch("value") >> imatch("=") >> val; 
 
if(ss) 
{ std::cout << "read value = " << val << std::endl; } 
else 
{ std::cout << "read failed" << std::endl; }

这在构造函数调用中使用类模板参数推导。它工作得很好……在 C++17 中。问题是这段代码需要一路编译回RHEL6,它最多只支持-std=c++0x(C++11的一个子集)。

编写和使用此类的最简洁的方法是什么,以便用户可以轻松地移植他们的sscanf() 调用以使用它,而无需访问 C++17?

【问题讨论】:

  • 您真的需要在呼叫站点使用 Char 模板参数吗?我会简单地使用 c_imatch = imatch

标签: c++ gcc c++17 rhel


【解决方案1】:

一种常见的解决方法是提供一个可以依赖传统模板参数推导的make_xx 函数:

template <typename T>
imatch<T> make_imatch(const T* t) { 
    return imatch<T>(t);
}

【讨论】:

  • 那么你将如何使用它呢? ss &gt;&gt; make_imatch&lt;char&gt;("somestring") &gt;&gt; make_imatch&lt;char&gt;("someotherstring") &gt;&gt; val?
  • @matoro 我修正了单个字符的错字(或疏忽);它现在可以与 make_imatch("somestring") 一起使用,而根本没有 &lt;&gt;。
  • @matoro - 无需显式调用make_imatch() 的模板类型; make_xx 函数的诀窍就是允许模板推导,所以ss &gt;&gt; make_imatch("somestring") &gt;&gt; make_imatch("someotherstring") &gt;&gt; val
  • 啊,很好用,谢谢!比我希望的要冗长一些,但我会为它想一个更短的名字。
猜你喜欢
  • 2020-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 1970-01-01
  • 2017-12-30
  • 1970-01-01
  • 2018-02-15
  • 1970-01-01
相关资源
最近更新 更多