模板专用 class 静态方法是否占用存储空间?

Do template specialized class with static methods occupy storage?

(标题乱七八糟,很抱歉。我很乐意接受改进建议。)

我会尽量直截了当。我有以下代码:

file1.hpp

template <class val_t>
struct MatOps;

file2.hpp:

#include "file1.hpp"
template <> struct MatOps<float>{
  static void method1(){
    // Do something
  }
  static void method2(){
    // Do something
  }
  static void method3(){
    // Do something
  }
}

File3.hpp:

#include "file1.hpp"
template <> struct MatOps<double>{
  static void method1(){
    // Do something different
  }
  static void method2(){
    // Do something different
  }
  static void method3(){
    // Do something different
  }
}

main.cpp

#include "file2.hpp"
#include "file3.hpp"

int main(){
  float a,b,c,d;

  MatOps<float>::method1(a,b,...);
  MatOps<float>::method2(c,d,...);

  return 0;
}

问题:

  1. 使用显式专业化MatOps<double>。然而, MatOps<double> 真的实例化了吗?或者更粗略地说:包含 file3.hpp 是否会占用任何存储空间?
  2. 没有使用MatOps<float>::method3(),但我正在使用class中的其他方法。由于我明确使用 MatOps<float>,编译器是否为 MatOps<float>::method3() 生成代码?

基本原理: 我被要求遵循 MISRA C++:2003 标准中的一些准则。虽然过时了,但我一直被鼓励使用其中任何合​​理的东西。特别是,有一条规则是:

Header files should be used to declare objects, functinos, inline functions, function templates, typedefs, macros, classes, and class templates and shall not contain or produce definitions of objects or functions (or fragments of functions or objects) that occupy storage.

A header file is considered to be any file that is included via the #include directive, regardless of name or suffix.

我的代码是大量模板化的,因此我可以根据此规则包含任何文件。当我进行完全专业化时,我的问题就来了(我只做了其中的两个:file2.hpp 和 file3.hpp 中列出的那些)。什么是 完整模板专业化?即使不使用它们,是否为它们生成代码?最终,它们是否占用存储空间?

为了回答你的第一个问题,我引用以下来自cppreference.com的内容:

A class template by itself is not a type, or an object, or any other entity. No code is generated from a source file that contains only template definitions. In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).

包含 file3.hpp 不会自行生成代码。

至于第二部分,同样来自同一页,

When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, and this particular type has not been explicitly instantiated, implicit instantiation occurs. For example, when an object of this type is constructed, but not when a pointer to this type is constructed.

This applies to the members of the class template: unless the member is used in the program, it is not instantiated, and does not require a definition.

除非您对 class 模板进行显式实例化,否则 class 模板的各个成员函数将不会被实例化,,编译器不会为 MatOps<float>::method3().

生成代码