首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >外部模板c++的问题

外部模板c++的问题
EN

Stack Overflow用户
提问于 2018-05-30 05:37:59
回答 1查看 59关注 0票数 1

我使用的是C++,而我在使用外部模板时遇到了困难。与C#相反,在C++中整个模板实现非常麻烦:(

template_test.hpp

代码语言:javascript
复制
template<class T>
class CFoo {
        public:
            T Foo_Func(const T& test);
};

template_test.cpp

代码语言:javascript
复制
#include "Template_Test.hpp"
    template<class T>
    T CFoo<T>::Foo_Func(const T& test)
    {
            return test;
    }

template_test2.hpp

代码语言:javascript
复制
#include "Template_Test.hpp"
extern template class CFoo<int>;
int Template_Tests();

template_test2.cpp

代码语言:javascript
复制
#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 int test;放在头文件中,将int test = 0放在源文件中。)

感谢您的支持:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-30 07:20:42

解决方案1

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

代码语言:javascript
复制
template<class T>
class CFoo {
public:
    T Foo_Func(const T& test) {
        return test;
    }
};

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

你需要知道的一件重要的事情--这个问题的解决方案在不同的IDE之间有很大的不同,但这个简单的解决方案在大多数IDE中都有效(如果不是总是的话)。

解决方案2

另一种选择是,如果您仍然希望将实现与定义分开,则可以包括.cpp文件以及.hpp/.h文件:

template_test2.hpp

代码语言:javascript
复制
#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文件的末尾,添加以下行:

代码语言:javascript
复制
template class CFoo<int>;

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

我希望你会发现它是有帮助的,Korel。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50593345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档