使用别名显式模板实例化?

met*_*fox 6 c++ templates visual-studio-2015 c++17

头文件.h

template <int>
class FiniteElement {
public:
    int GetDOF();
};

using FiniteElement2D = FiniteElement<3>;
using FiniteElement3D = FiniteElement<6>;
Run Code Online (Sandbox Code Playgroud)

源码.cpp

#include "Header.h"

//template class FiniteElement<3>;
//template class FiniteElement<6>;
template FiniteElement2D;  // Using alias for explicit template instantiation !!!
template FiniteElement3D;

template <int DOF>
int FiniteElement<DOF>::GetDOF() {
    return DOF;
}
Run Code Online (Sandbox Code Playgroud)

主要.cpp

#include "Header.h"
#include <iostream>

int main() {
    FiniteElement3D Elem;
    std::cout << Elem.GetDOF();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,上面的程序使用 Visual Studio 2015 Update 3 进行编译和链接。我喜欢允许使用别名进行显式模板实例化的想法,但它似乎不适用于 gcc 或 clang。

这是即将推出的标准的功能还是 VS 的特定功能?

Ser*_*eyA 1

答案已经在评论中给出了,但是稍微隐蔽了一点,所以我在这里扩展一下。

MSVC 编译器在这种情况下的工作方式几乎就像在程序代码中进行文本替换一样。FiniteElement2D它基本上替换了所有文本FiniteElement<3>- 这样显式实例化就可以很好地为您工作。

另一方面,其他编译器为 构建适当的抽象语法树typedef,因此,别名的使用不会扩展到显式模板实例化。

附带说明一下,我不确定您希望从语法中获得什么样的好处。

  • 我只是碰巧在我的代码中执行了与OP相同的语法。在msvc中编译成功后也遇到了gcc编译问题。好处是,它只需要在一处进行更改(即 in using 声明),并且它将传播到显式模板实例化。如果没有这种方法,您需要在两个地方进行更改。在 1 个地方进行更改几乎总是比在 2 个地方进行更改更干净。 (2认同)