metalfox metalfox - 1 year ago 101
C++ Question

Explicit template instantiation using alias?


template <int>
class FiniteElement
int GetDOF();

using FiniteElement2D= FiniteElement<3>;
using FiniteElement3D= FiniteElement<6>;


#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; }


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

int main()
FiniteElement3D Elem;

std::cout << Elem.GetDOF();

return 0;

To my surprise, the above program compiles and links with Visual Studio 2015 Update 3. I like the idea of allowing alias to be used for explicit template instantiation, but it doesn't seem to work with gcc or clang.

Is it a feature of the forthcoming standard or something specific of VS?

Answer Source

The answer was given in the comments, but in slightly disguised way, so I will expand it here.

The way MSVC compiler works in this case is almost like doing textual replacement in the program code. It basically replaces all text of FiniteElement2D with FiniteElement<3> - this way the explicit instantiation works fine for you.

Other compilers, on the other hand, build a proper abstract syntax tree for the typedef, and as a result, the alias usage doesn't expand to explicit template instantiation.

As a side note, I am not sure what kind of benefit you expect to get from your syntax.