如何从之前定义的另一个函数调用函数模板?

mat*_*atn -1 c++

我有两个函数模板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

}
Run Code Online (Sandbox Code Playgroud)

来自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) {
      ^
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 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
}
Run Code Online (Sandbox Code Playgroud)

(现场演示)