且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以默认参数为模板类型的函数

更新时间:2023-11-30 19:00:46

根据 C++ 标准第 8.3.6 节,

According to section 8.3.6 of the C++ standard,

如果在参数声明中指定了表达式,则该表达式将用作默认参数.在缺少尾随参数的调用中将使用默认参数.

If an expression is specified in a parameter declaration this expression is used as a default argument. Default arguments will be used in calls where trailing arguments are missing.

由于A 不是函数调用,默认参数被忽略.事实上,除了函数的调用,它们在所有上下文中都被忽略,例如

Since A<foo1> is not a call of the function, default arguments are ignored. In fact, they are ignored in all contexts except the calls of the function, for example

typedef void (*FFF)();
FFF x = foo1;

不会编译,并产生与您尝试使用 foo1 作为模板参数时得到的相同消息:

will not compile, and produce the same message that you get when trying to use foo1 as a template parameter:

error: invalid conversion from ‘void (*)(int)’ to ‘void (*)()’

这是有道理的,因为评估默认参数是调用中的一个单独步骤:

This makes sense, because evaluating default arguments is a separate step in the invocation:

8.3.6.9:每次调用函数时都会评估默认参数.

8.3.6.9: Default arguments will be evaluated each time the function is called.

默认参数的存在不会改变函数的签名.例如,您不能使用带有默认参数的单参数函数来覆盖无参数虚拟成员函数.

The presence of default arguments does not alter the signature of your function. For example, you cannot use a single-argument function with a default argument to override a no-argument virtual member function.