我std::reference_wrapper
对构建类型(double
)和用户定义的类型(std::string
)有以下用途。
为什么在流运算符的情况下它们的行为有所不同?
#include<functional> //reference wrapper
#include<iostream>
void fd(double& d){}
void fs(std::string& s){}
int main(){
double D = 5.;
std::reference_wrapper<double> DR(D);
std::cout << "DR = " << DR << std::endl; //ok
fd(DR); // ok
std::string S = "hello";
std::reference_wrapper<std::string> SR(S);
std::cout << "SR = " << static_cast<std::string&>(SR) << std::endl; // ok
std::cout << "SR = " << SR << std::endl; // error: invalid operands to binary expression ('basic_ostream<char, std::char_traits<char> >' and 'std::reference_wrapper<std::string>')
fs(SR); // ok
}
http://coliru.stacked-crooked.com/a/fc4c614d6b7da690
为什么在第一种情况下将DR转换为double并打印,而在第二种情况下却没有呢?有没有解决的办法?
好的,我现在看到的是,在ostream情况下,我试图调用无法解析的模板化函数:
#include<functional> //reference wrapper
void double_fun(double const& t){};
template<class C>
void string_fun(std::basic_string<C> const& t){};
int main(){
double D = 5.;
std::reference_wrapper<double> DR(D);
double_fun(DR); //ok
std::string S = "hello";
std::reference_wrapper<std::string> SR(S);
string_fun(SR); // error: no matching function for call to 'string_fun'
string_fun(SR.get()); // ok
string_fun(static_cast<std::string&>(SR)); // ok
string_fun(*&SR); // would be ok if `std::reference_wrapper` was designed/coded differently, see http://stackoverflow.com/a/34144470/225186
}
对于第一部分,TC给了您答案。也就是说,basic_string的operator <<是模板化的,并且模板参数推导不会通过隐式转换进行查找。
SR.get()
如果您不想显式static_cast
引用到引用包装器,则可以选择调用。
现在,对于第二部分,string_fun
将std::basic_string<C>
对象作为输入参数。你打电话时:
string_fun(SR);
与SR
作为它的类型的输入参数std::reference_wrapper<std::string>
,自然你就会得到一个类型不匹配。
您可以做的是提供额外的重载:
template<class C>
void string_fun(std::reference_wrapper<std::basic_string<C>> const& t) {
};
或者,如果您想要更统一的处理方式,则可以定义您的string_fun
模板模板参数,并使用类似下面的类型特征魔术来解析类型:
template<template<typename...> class C, typename T>
void
string_fun(C<T> const &t) {
std::cout <<
static_cast<std::conditional_t<
std::is_same<
std::reference_wrapper<T>, C<T>>::value, T, std::basic_string<T>>>(t) << std::endl;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句