我有一个这样定义的模板类:
template <class T>
class Command {
public:
virtual T HandleSuccess(std::string response) = 0;
virtual std::string FullCommand() const = 0;
// ... other methods here ...
};
C++ 允许我创建模板类的非模板子类吗?我的意思是我可以做这样的事情吗:
class NoopCommand : public Command<NoopResult> {
public:
NoopResult HandleSuccess(std::string response);
std::string FullCommand() const;
// ... other methods here ...
};
这对我不起作用,因为它说以下虚函数未定义:
T admix::Command<T>::HandleSuccess(std::string) [with T = admix::NoopResult]
std::string admix::Command<T>::FullCommand() const [with T = admix::NoopResult]
如何为给定的 T 专门定义它们?
最佳答案
正如我们在 IRC 中发现的那样,那是因为你有
- 让你的函数不纯粹
- 对派生对象部分进行切片。因此调用了基类函数,因为该对象不再是一个完整的派生对象。
(以下是我对你问题的早期版本的怀疑 - 我保留它以供进一步考虑并保持评论有意义)
<子> 我认为这里的问题是编译器可以自由实例化类模板的任何虚函数成员,即使它没有被使用(即没有被调用)。实例化函数需要提供函数定义。尝试将其添加到 header 中,编译器将在其中找到它们并实例化来自以下内容的定义:
template<typename T>
T Command<T>::HandleSuccess(std::string response) { /* put some default action ... */ }
template<typename T>
std::string Command<T>::FullCommand() const { /* put some default action ... */ }
C++ 标准 14.7.1/9
:
An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class or a static data member of a class template that does not require instantiation. It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated.
关于c++ - 是否可以将非模板类子类化为模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1622694/