C++ 模板数组类 : Error generation depends on whether it inherits an interface or not

标签 c++ templates inheritance interface

抱歉标题含糊不清 - 我不知道如何简短地描述我的问题。我一直在玩复合设计模式,遇到了以下情况。假设我有一个接口(interface)

class interface
{
public:
   virtual ~interface() { }
   virtual void methodA(const uint8_t* ptr) = 0;
};

然后说我有一个遵循这个接口(interface)的模板类(这只是一个简单的例子,我知道它没有多大意义)。

template <typename T>
class customArray
{
public:
   void methodA(const uint8_t* ptr)
   {
      if (m_data.size())
         m_data[0].methodA(ptr);
   }

   int methodB(uint8_t* ptr)
   {
      if (m_data.size())
         return m_data[0].methodB(ptr);

      return 0;
   }

   void push_back(const T& elm)
   {
      m_data.push_back(elm);
   }

private:
   std::vector<T> m_data;
};

注意模板类不继承接口(interface)。现在,如果我定义一些简单的类

class customPrimitive
{
public:
   int methodB(uint8_t* ptr)
   {
      (void)ptr;
      return -1337;
   }
};

然后像这样使用它

customArray<customPrimitive> arr;
arr.push_back(customPrimitive());
printf("Got %i\n", arr.methodB(NULL)); // Prints -1337
// arr.methodA(NULL); This will make build fail

显然,如果我尝试调用 methodA,构建应该会失败。但是为什么当我避免调用它时它不会失败?

此外,如果我让数组继承接口(interface),为什么构建会失败?在这种情况下,无论我是否调用该方法,它都会发生。

如果有人能提供一些见解,我将不胜感激。

谢谢,

最佳答案

因为您没有调用它,所以编译器正在优化 customArray.methodA

关于C++ 模板数组类 : Error generation depends on whether it inherits an interface or not,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911480/

相关文章:

inheritance - Java & Guice - 如何处理继承和抽象?

c++ - 派生赋值运算符从基数调用

c++ - 在 lambda 中使用类模板参数时出现编译错误

php - 使用 Smarty 或 Backbone.js 制作 javascript 模板

c++ - Tesseract:如何导出文本和边界框?

c++ - 创建恒定大小 vector 的恒定大小 vector

c++ - 定义模板类的静态常量变量

c++ - 转发声明 : templates and inheritance

c++ - DirectShow 和 OpenCV。读取视频文件并处理

c++ - 为什么虚函数会破坏我的转换?