以默认参数为模板类型的函数 [英] Function with default parameter as template type
问题描述
我正在尝试使用带有默认参数的函数作为函数指针模板参数:
I am trying to use a function with a default argument as a function pointer template parameter:
template <void (*F)()>
class A {};
void foo1(int a = 0) {}
void foo2() {}
int main()
{
//A<foo1> a1; <-- doesn't work
A<foo2> a2;
}
编译错误是:
main.cpp:7:7: 错误:无法将模板参数‘foo1’转换为‘void (*)()’
main.cpp:7:7: error: could not convert template argument ‘foo1’ to ‘void (*)()’
是否有特定的语法可以使其工作?还是特定的语言限制?否则,替代方法是使用两个单独的函数而不是默认参数:
Is there specific syntax for this to work? Or a specific language limitation? Otherwise, the alternative is to have two separate functions instead of a default parameter:
void foo1(int a) {}
void foo1() { foo1(0); }
更新我知道签名是不同的,但我想知道是否有一种方法可以方便地完成这项工作,而无需修改所有带有默认参数的函数?
Update I understand that the signatures are different, but I'm wondering if there is a way to make this work conveniently without needing to modify all the functions with default parameters?
推荐答案
根据 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.
这篇关于以默认参数为模板类型的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!