Edit:这不是链接问题的重复,因为我使用的是显式实例化,并且只有特定类型的成员函数不链接(其他函数会链接)。
以下代码可以编译但无法链接,我不明白为什么。
它显式实例化Vector
类来限制可能的参数数量T
因此隐藏了定义Vector<T>
在 .cpp 文件中。
// fwd_decl.hpp
#pragma once
template<typename T>
struct Vector; // Forward declare Vector to be used in other headers
// Vector.hpp
#pragma once
#include "fwd_decl.hpp"
template<typename T>
struct Vector
{
template<typename U> // To allow for other types than T to be used
Vector operator+(const Vector<U> & other) const;
T x;
T y;
// more stuff..
};
// Vector.cpp
#include "Vector.hpp"
template<typename T>
template<typename U>
Vector<T> Vector<T>::operator+(const Vector<U> & other) const
{
return { static_cast<T>(x + other.x), static_cast<T>(y + other.y) };
}
template struct Vector<int>; // Explicitly instantiate Vector<T> with int
// main.cpp
#include "Vector.hpp"
int main()
{
Vector<int> b = Vector<int>{ 2, 3 } + Vector<int>{ 4, 5 };
}
我收到的错误是:
1>main.obj : error LNK2001: unresolved external symbol "public: struct Vector<int> __thiscall Vector<int>::operator+<int>(struct Vector<int> const &)const " (??$?HH@?$Vector@H@@QBE?AU0@ABU0@@Z)
我正在编译VC++ 17 in VS 15.9.4.
请注意,呼叫成员Vector<int>
那些不是函数模板的链接可以正常链接。
您应该使用该方法的显式实例化template<typename T> template<typename U> Vector<T> Vector<T>::operator+(const Vector<U> & other) const
(对于所有可能的对T
and U
)除了显式实例化Vector<T>
class:
template Vector<int> Vector<int>::operator+(const Vector<short> & other) const;
您也可以简单地移动Vector<T>::operator+
方法到头文件中。
在 C++11 中extern template
指令被引入。您可以在头文件中使用它Vector<T>
类(如@说故事的人 评论中建议):
extern template struct Vector<int>;
...防止编译器实例化Vector<T>
每个翻译单元中都使用其专业化的类。当然一样extern template
指令也可用于所有Vector<T>::operator+
明确实例化的专业化.cpp
file.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)