Why do these two code snippets have the same effect?

Ede*_*dee 8 c++ decltype ternary c++17

template <typename T1, typename T2>
auto max (T1 a, T2 b) -> decltype(b<a?a:b);
Run Code Online (Sandbox Code Playgroud)
template <typename T1, typename T2>
auto max (T1 a, T2 b) -> decltype(true?a:b);
Run Code Online (Sandbox Code Playgroud)

I do not understand why these two code snippets can have the same effect. Plz give me some hint and a underlying explanation.

Cheers.

max*_*x66 14

因为三元运算符返回的类型是根据第二个和第三个参数的类型而不是第一个参数的值确定的。

您可以使用以下代码进行验证

#include <type_traits>

int main ()
 {
   auto x = true ? 1 : 2l;

   static_assert( std::is_same<decltype(x), long>::value, "!" );
 }
Run Code Online (Sandbox Code Playgroud)

true ? 1 : 2l回报永远不重要1; 三元运算符返回1int)和2llong)之间的通用类型。那是long

换句话说:(目前)没有constexpr三元运算符。


mol*_*ilo 6

条件表达式的类型不取决于条件是否为真。

decltype(b<a?a:b)是表达式的类型,b<a?a:b始终相同。
这不是非此即彼decltype(a)decltype(b)取决于价值b<a

请注意,decltype永远不会对您提供的表达式进行求值-仅确定其类型,并且在编译时确定它。

非正式地:

  • 如果a可以转换为的类型b,则表达式的类型与b
  • 如果b可以转换为的类型a,则表达式的类型与a
  • 否则,该表达式为错误类型。

(有关标准转换和yada-yada的细节也很多,但这是要点。)

例如,由于没有可以提供notgood类型的有效转换,因此不会编译该代码:

int main()
{
     decltype(true ? "hello" : 123.4) notgood;
}
Run Code Online (Sandbox Code Playgroud)

尽管这将编译,运行并定义良好,因为永远不会评估无效的取消引用:

int main()
{
    decltype(*(int*)0 + 1)` x = 0;
    return x;
}
Run Code Online (Sandbox Code Playgroud)

  • 除了这些答案中提供的详细信息之外,很难解释其他任何内容。最重要的一点是,条件表达式的“类型”不依赖于所涉及的任何“值”。 (2认同)