gpt4 book ai didi

c++11 - 为什么 reference_wrapper 对于内置类型的行为不同?

转载 作者:行者123 更新时间:2023-12-04 21:11:09 25 4
gpt4 key购买 nike

我有以下使用 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_funstd::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) {

};

Live Demo

或者,如果您想要更统一的处理方式,您可以定义您的 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;
}

Live Demo

关于c++11 - 为什么 reference_wrapper 对于内置类型的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34144326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com