gpt4 book ai didi

c++ - 模板类实例化如何与类继承一起工作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:37:30 31 4
gpt4 key购买 nike

代码

我有以下 2 个类的片段,带有单独的源文件和头文件。派生类是模板类。

handler.h

class BaseHandler {
public:
BaseHandler(){}
BaseHandler(const std::string& directive);
virtual ~BaseHandler();
virtual bool operator()();
private:
const std::string m_directive;
};

template<typename C>
class DirectiveHandler : public BaseHandler {
public:
DirectiveHandler(const std::string& directive);
~DirectiveHandler();
bool operator()() override;
private:
std::vector<C> m_configurations;
};

handler.cpp

#include "handler.h"

BaseHandler::BaseHandler(const std::string& directive) : m_directive(directive) {};

BaseHandler::~BaseHandler(){};

template<typename C>
DirectiveHandler<C>::DirectiveHandler(const std::string& directive) :
BaseHandler(directive) {};

template<typename C>
bool DirectiveHandler<C>::operator()(){ return true; };

main.cpp

#include "handler.h"

template class DirectiveHandler<double>; //explicit template instantiation

int main(int argc, char *argv[]){
....

据我了解,我需要在定义模板后对其进行实例化,这可以隐式发生(省略 template class DirectiveHandler<double>; )或显式发生。我假设隐式实例化由于各自源文件和头文件中定义和声明的分离而失败。

使用上面的 main.cpp 片段,我有以下警告:

  1. warning: explicit template instantiation DirectiveHandler<double> will emit a vtable in every translation unit

  2. warning: instantiation of function DirectiveHandler<double>::operator() required here, but no definition available

如果改变template class DirectiveHandler<double>extern template class DirectiveHandler<double>;两个警告都消失了。我明白为什么警告 2 被清除了,因为模板类驻留在 handler.cpp 中。我也看不出它是如何清除警告 1 的。

问题

为什么要添加extern关键字清除警告 1(见上文)?

最佳答案

我假设您正在使用 CLang 编译代码? (据我所知,这是 CLang 警告,除非 g++ 也开始发出它)。

无论如何,所问问题的答案(我只需要假设 OP 理解其他一切)是一个简单的事实 template class DirectiveHandler<double>; - 这是隐式模板实例化定义,它产生 vtbl等等。 (针对 .cpp 文件发出警告的事实可能实际上是一个错误,但 OP 不会询问它)。

另一方面,extern template class DirectiveHandler<double>;不是定义。这是一个声明,它本身不会触发 vptr的一代 - 因此您看不到任何警告。

关于c++ - 模板类实例化如何与类继承一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54132890/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com