传递带有括号的 typedef 作为参数

Passing typedef with parenthesis as an argument

本文关键字:typedef 参数      更新时间:2023-10-16

我找到了一段带有奇怪参数的代码,这是一种类型:

#include <iostream>
using namespace std;
template<class T>
int function1(T count,double)
{
    cout<<"function1 is called"<<endl;
    return 1111;
}
int main()
{
    typedef int aaaa;
    function1(1,aaaa()); 
}

而这个函数的输出是

函数 1 被调用

想知道当参数是一种类型时是什么意思?为什么我应该给函数 aaaa() 和不带括号的 aaaa 给出编译器错误?

error: expected primary-expression before ‘)’ token
  function1(1,aaaa); 
                  ^

function1(1, aaaa)等效于function1(1, int) - 您正在尝试将类型作为参数传递,该参数格式不正确。

function1(1,aaaa()) aaaa() 中创建具有值0的临时int。例如,请参阅C++14草案N4140 [expr.type.conv]/2:

表达式 T() ,其中 T 是非数组完整对象类型或(可能符合 cv 条件的)void 类型的简单类型说明符或类型名说明符,创建指定类型的 prvalue,其值是通过值初始化 (8.5) 生成的 T 类型的对象

;
T();其中

T是任何类型的,则会创建类型为 T 的无名临时。创建的对象将被值初始化。当应用于aaaainttypedef)时,将创建一个临时int并分配值0