首页 > 解决方案 > 外部模板c ++的问题

问题描述

我正在使用 C++,我在使用外部模板时遇到了困难。与 C# 相反,整个模板实现在 C++ 中真的很讨厌 :(

模板测试.hpp

template<class T>
class CFoo {
        public:
            T Foo_Func(const T& test);
};

模板测试.cpp

#include "Template_Test.hpp"
    template<class T>
    T CFoo<T>::Foo_Func(const T& test)
    {
            return test;
    }

模板测试2.hpp

#include "Template_Test.hpp"
extern template class CFoo<int>;
int Template_Tests();

模板测试2.cpp

#include "Template_Test2.hpp"
int Template_Tests()
{

    CFoo<int> foo_instance;

    //this causes an undefined reference
    int res = foo_instance.Foo_Func(1);

    return res;
}

为什么链接器找不到我的功能。我认为 extern 模板的工作原理与 extern 变量相同。(放入extern int test;头文件和int test = 0源文件。)

谢谢你的支持:)

标签: c++

解决方案


解决方案 1

解决这个问题的一种方法是在没有函数定义的情况下实现模板类的函数。在这种情况下:

template<class T>
class CFoo {
public:
    T Foo_Func(const T& test) {
        return test;
    }
};

然后,你甚至不需要这个extern部分。我知道你的程序员一直在告诉你要避免这种情况,并且总是将你的类函数的定义和它们的实现分开——但在 c++ 中的模板案例中,这是解决这种语言巨大问题的最简单的解决方案。

您需要知道的一件重要事情 - 不同 IDE 之间针对此问题的解决方案存在很大差异,但这种简单的解决方案适用于大多数 IDE(如果并非总是如此)。

解决方案 2

另一种选择,如果您仍想将实现与定义分开,您可以包含 .cpp 文件以及 .hpp/.h 文件:

模板测试2.hpp

#include "Template_Test.hpp"
#include "Template_Test.cpp"
/*extern template class CFoo<int>;*/ // Again, you don't need this extern
int Template_Tests();

解决方案 3

这是与您尝试的方式最接近的方式。在template_test.cpp文件末尾,添加以下行:

template class CFoo<int>;

extern template class CFoo<int>;并从template_test2.hpp文件中删除该行。

我希望你会发现它有帮助,科雷尔。


推荐阅读