17

我收到以下编译器¹消息

main.cpp: In instantiation of ‘void fkt(Foo) [with Foo = int]’:
main.cpp:5:7:   required from here

无论如何都会创建二进制文件,因此这不是错误。但它也没有被标记为警告。这是什么消息,为什么我会收到它?

我将代码简化为以下示例

template <typename Foo>
void fkt(Foo f) {}

int main() {
  fkt(1);
  return 0;
}

¹ gcc 4.7.2

编辑:这里重现的步骤:

% cat main.cpp
template <typename Foo>
void fkt(Foo f) {}

int main() {
  fkt(1);
  return 0;
}
% g++ -Wall  -Wextra main.cpp
main.cpp: In instantiation of ‘void fkt(Foo) [with Foo = int]’:
main.cpp:5:7:   required from here
main.cpp:2:6: warning: unused parameter ‘f’ [-Wunused-parameter]
4

1 回答 1

26
main.cpp: In instantiation of ‘void fkt(Foo) [with Foo = int]’:
main.cpp:5:7:   required from here
main.cpp:2:6: warning: unused parameter ‘f’ [-Wunused-parameter]

This is all one warning. You are getting a 3 line warning about an unused parameter. The first two lines are the compiler attempting to help you identify the cause of the warning. Here's an English translation:

In the instantiation of fkt with template argument Foo as int which was required by line 5 column 7, you have an unused parameter called f.

fkt is a function template. Templates have to be instantiated with the given template arguments. For example, if you use fkt<int>, the fkt function template is instantiated with Foo as int. If you use fkt<float>, the fkt function template is instantiated with Foo as float.

In particular, this first line of this message is telling you that the warning occurs inside fkt which was instantiated with Foo as int. The second line of the warning tells you that instantiation occurred on line 5. That corresponds to this line:

fkt(1);

This is instantiating fkt with Foo as int because the template argument Foo is being deduced from the type of the argument you're giving. Since you're passing 1, Foo is deduced to be int.

于 2013-03-26T18:50:06.393 回答