c++模板的问题解析-问题2

来源:互联网 发布:java的框架 编辑:程序博客网 时间:2024/05/01 19:53

问题起源

class Timer {public:    Timer(){}};class TimeKeeper {public:    TimeKeeper(const Timer& t){}    TimeKeeper(){}    std::string time;    std::string get_time(){ return time; }    friend std::istream& operator>> (std::istream& is, TimeKeeper& sr);};std::istream& operator>>(std::istream& is, TimeKeeper& sr){    is >> sr.time;    getline(is, sr.time);    return is;}int main() {    TimeKeeper time_keeper(Timer()); //no.1    TimeKeeper time_keeper_();//no.2    std::string t;    std::istringstream sin(t);    sin >> time_keeper;//no.3    time_keeper.get_time();//no.4    return 0;}

上述代码编译是不会通过的,编号no3、4处代码会报错,例如gcc4.8在no.3处报错— error: ambiguous overload for ‘operator>>’ (operand types are ‘std::istringstream {aka std::basic_istringstream}’ and ‘TimeKeeper(Timer (*)())’).

解答
这是c++标准的一个特性,称为Most vexing parse。
无论是no.1还是no.2都可以被解析为一个变量或者一个函数声明。
g++编译器会认为no.3是模棱两可的,因为如果是一个变量则调用自定义的>>重载,如果是一个函数声明,c++也提供了模板重载函数来接收anything为右值参数:

template<typename CharT, typename TraitsT, typename T>basic_istream<CharT, TraitsT>&operator>>(basic_istream<CharT, TraitsT>&& istr, T&&);

而有些编译器会默认这是函数声明,而该函数类型不能绑定为右值参数,于是就会出现如下错误:error: cannot bind ‘std::basic_istream’ lvalue to ‘std::basic_istream&&’。
因此,为了避免歧义,根据实际目的no.1和no.2应做相应修改:

no.1 -> TimeKeeper time_keeper((Timer()))no.2 -> TimeKeeper time_keeper_ or TimeKeeper time_keeper_{} or TimeKeeper time_keeper_=TimeKeeper()
1 0