我有两个功能模板A和B。我在同一文件中定义A,然后定义B。现在,我想在A中呼叫B。如何实现?正常功能原型在这种情况下不起作用。 (请假定您不能更改A和B的顺序或拆分文件。)
#include <iostream>
template <class Type>
Type A(Type x) {
return 2 * B(x);
}
template <class Type>
Type B(Type x) {
return 3 * x;
}
int main() {
int x = 3;
std::cout << A(x) << "\n"; //=> ERROR
}
g ++中的错误:
test.cpp: In instantiation of ‘Type A(Type) [with Type = int]’:
test.cpp:40:21: required from here
test.cpp:29:17: error: ‘B’ was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]
return 2 * B(x);
~^~~
test.cpp:33:6: note: ‘template<class Type> Type B(Type)’ declared here, later in the translation unit
Type B(Type x) {
^
答案 0 :(得分:5)
如果用原型的意思是声明,那么在这种情况下肯定可以工作!
您可以声明一个函数模板:
#include <iostream>
// Non-defining declaration B
template <class Type>
Type B(Type x);
// Defining declaration A
template <class Type>
Type A(Type x) {
return 2 * B(x);
}
// Defining declaration B
template <class Type>
Type B(Type x) {
return 3 * x;
}
int main() {
int x = 3;
std::cout << A(x) << "\n"; //=> NO ERROR
}