函数指针类型的c++模板调用

时间:2021-04-29 21:40:03

If I have type declarations like

如果我有像这样的类型声明

typedef void (*command)();

template <command c>
void execute() {
   c();
}

void task() { /* some piece of code */ }

then

然后

execute<task>();

will compile and behaves as expected. However if I define the template as

将按照预期编译并执行。但是如果我将模板定义为

template <command c>
void execute() {
   command();
}

it still compiles. I did this by accident. Now I am confused of what the second version would be expected to do.

它仍然编译。我是偶然做的。现在我对第二个版本会做什么感到困惑。

2 个解决方案

#1


8  

In C++

在c++中

type_name()

is an expression that creates a default-initialized instance of type_name.

是创建type_name默认初始化实例的表达式。

For natives types there are implicitly defined default constructors, so for example

对于本机类型,有隐式定义的默认构造函数,例如

int();

is a valid C++ statement (just creates an int and throws it away).

是一个有效的c++语句(只是创建一个int并将其丢弃)。

g++ with full warnings on emits a diagnostic message because it's a suspect (possibly unintended) operation, but the code is valid and there can even be programs depending on it (if the type is a user-defined type and the constructor of the instance has side effects).

带有完整警告的g++会发出诊断消息,因为它是一个可疑的(可能是无意的)操作,但是代码是有效的,甚至可以有依赖于它的程序(如果类型是用户定义的类型,并且实例的构造函数具有副作用)。

#2


4  

command();

It creates a temporary object like TYPE(); and compiler omits it as an unused variable.

它创建一个类似TYPE()的临时对象;编译器将它省略为未使用的变量。

warning: statement has no effect [-Wunused-value]
     command();
     ^

You should turn on -Wall compiler's option. Live code.

您应该打开-Wall编译器的选项。生活的代码。

#1


8  

In C++

在c++中

type_name()

is an expression that creates a default-initialized instance of type_name.

是创建type_name默认初始化实例的表达式。

For natives types there are implicitly defined default constructors, so for example

对于本机类型,有隐式定义的默认构造函数,例如

int();

is a valid C++ statement (just creates an int and throws it away).

是一个有效的c++语句(只是创建一个int并将其丢弃)。

g++ with full warnings on emits a diagnostic message because it's a suspect (possibly unintended) operation, but the code is valid and there can even be programs depending on it (if the type is a user-defined type and the constructor of the instance has side effects).

带有完整警告的g++会发出诊断消息,因为它是一个可疑的(可能是无意的)操作,但是代码是有效的,甚至可以有依赖于它的程序(如果类型是用户定义的类型,并且实例的构造函数具有副作用)。

#2


4  

command();

It creates a temporary object like TYPE(); and compiler omits it as an unused variable.

它创建一个类似TYPE()的临时对象;编译器将它省略为未使用的变量。

warning: statement has no effect [-Wunused-value]
     command();
     ^

You should turn on -Wall compiler's option. Live code.

您应该打开-Wall编译器的选项。生活的代码。