c++ - 是否可以将非模板类子类化为模板类?

标签 c++ templates subclass

我有一个这样定义的模板类:

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 中发现的那样,那是因为你有

  1. 让你的函数不纯粹
  2. 对派生对象部分进行切片。因此调用了基类函数,因为该对象不再是一个完整的派生对象。

(以下是我对你问题的早期版本的怀疑 - 我保留它以供进一步考虑并保持评论有意义)


<子> 我认为这里的问题是编译器可以自由实例化类模板的任何虚函数成员,即使它没有被使用(即没有被调用)。实例化函数需要提供函数定义。尝试将其添加到 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/

相关文章:

java - 将 unsigned char* 作为 byte[] 从 C++ 传递到 java 的最有效方法

C++ 可以发现错误

c++ - 如何将 string.erase() 与指针一起使用?

iphone - 简单的自定义 UIView 类已损坏

iOS:方法返回类型应该是类 X 的子类

python - 创建接受 kwargs 的 str(或 int 或 float 或 tuple)的 child

c++ - for (int x : temps) in C++ 的含义

c++ - 为什么我可以使用模板函数中的私有(private)方法

c++ - 任何从 c++filt demangled 输出中获取更多信息的方式

c++ - 如何使用 C++11 可变参数模板来定义由 vector 元组支持的元组 vector ?