我得到两个头:
header 1:
#ifndef CPPSH_A_H
#define CPPSH_A_H
class B;
class A {
public:
template<typename T>
void Function1() {
b_->Function2<int>();
}
template<typename T>
void Function2() {
}
private:
B* b_;
};
#endif //CPPSH_A_H
和header2:
#ifndef CPPSH_B_H
#define CPPSH_B_H
class A;
class B {
public:
template<typename T>
void Function1() {
a_->Function2<int>();
}
template<typename T>
void Function2() {
}
private:
A* a_;
};
#endif //CPPSH_B_H
并且您可以看到
a_
和b_
都是不完整的类型,并且对其的调用也受到了影响。如果这两个类是普通类,则可以将
Test()
实现移至源文件,然后包含适当的头。但是由于模板类/函数必须在 header 中定义和声明其实现,因此该如何处理?
最佳答案
您可以将两个 header 合并为一个,例如
// forward declaration
class B;
class A {
public:
// member function template declaration
template<typename T>
void Function1();
template<typename T>
void Function2() {
}
private:
B* b_;
};
class B {
public:
template<typename T>
void Function1() {
a_->Function2<T>();
}
template<typename T>
void Function2() {
}
private:
A* a_;
};
// member function template definition
template<typename T>
void A::Function1() {
b_->Function2<T>();
}
关于c++ - 模板类/函数中的交叉转发声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62274068/