【问题标题】:Why Can't I do decltype on an Extraction Operator为什么我不能对提取运算符执行 decltype
【发布时间】:2017-01-17 12:51:41
【问题描述】:

看来这应该是合法的:

decltype(declval<istream>().operator>>(declval<istream>(), declval<int>())) test;

但是当我尝试编译时,我得到:

错误 C2661:std::basic_istream&lt;char,std::char_traits&lt;char&gt;&gt;::operator &gt;&gt;:没有重载函数需要 2 个参数

我做错了吗?为什么这不评估为istream

编辑:

has been pointed 是因为istream&amp; istream::operator&gt;&gt;(int&amp;) 是一个方法,所以第一个值是自动传递的。

但是:decltype(declval&lt;istream&gt;().operator&gt;&gt;(declval&lt;int&gt;())) test; 错误:

错误 C2664:std::basic_istream&lt;char,std::char_traits&lt;char&gt;&gt; &amp;std::basic_istream&lt;char,std::char_traits&lt;char&gt;&gt;::operator &gt;&gt;(std::basic_streambuf&lt;char,std::char_traits&lt;char&gt;&gt; *):无法将参数 1 从 std::ios_base::iostate 转换为 std::basic_istream&lt;char,std::char_traits&lt;char&gt;&gt; &amp;(__cdecl *)(std::basic_istream&lt;char,std::char_traits&lt;char&gt;&gt; &amp;)

decltype(istream::operator &gt;&gt; (declval&lt;istream&gt;(), declval&lt;int&gt;())) test; 错误:

错误 C2661:std::basic_istream&lt;char,std::char_traits&lt;char&gt;&gt;::operator &gt;&gt;:没有重载函数需要 2 个参数

【问题讨论】:

  • istream 的成员 oparator&lt;&lt; 不会将 istream 作为第一个参数。
  • 为什么不直接使用decltype(std::declval&lt;std::ifstream &amp;&gt;() &gt;&gt; std::declval&lt;int&gt;())?这甚至适用于operator &gt;&gt;...的非成员重载...
  • istream&amp; istream::operator&lt;&lt;(const int&amp;) 不是一个东西,原因很明显。
  • @JonathanMee 我的意思是this。当然,这不能解决所有可能的问题,但是当您不确定某事的类型时,它显然可以解决问题。
  • @JonathanMee 确定你想要 :) 但你可以在运行时检查类型以在编译时应用知识:)

标签: c++ c++11 compile-time decltype extraction-operator


【解决方案1】:

采用intoperator&gt;&gt; 是一个成员函数(您当前正在使用成员 非成员函数的语法),它通过引用获取其参数(因此它可以填充它 - declval&lt;int&gt;() 给你一个int&amp;&amp;,你需要declval&lt;int&amp;&gt;() 来获得一个int&amp;):

using T = decltype(declval<istream>().operator>>(declval<int&>()));

最好不要直接调用运算符,这样您就不必担心哪个operator&lt;&lt; 是成员,哪个不是:

using T = decltype(declval<istream&>() >> declval<int&>());

【讨论】:

    猜你喜欢
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多