如何模拟C++17之前的类模板参数推导?

我正在努力sscanf()从 C++ 代码库中删除调用,并用std::stringstream此处描述的实现替换它们:https : //www.quora.com/Is-there-aC-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即可轻松移植调用以使用它?

回答

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

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


以上是如何模拟C++17之前的类模板参数推导?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>