如何防止特定模板的隐式模板实例化?

Aar*_*ham 8 c++ templates c++11

我想阻止特定模板化类的所有隐式模板实例化,以防止它被实例化到每个翻译单元中.

看起来我的选择是:

  1. 在gcc的命令行上使用-fno-implicit-templates.这会抑制所有隐式模板实例化,而不是我想要的.我只想为单个模板阻止它.
  2. 使用C++ 11"extern模板".但这只会抑制特定的显式实例化.我不想为每个可能的模板参数列表键入"extern模板"行,这个模板可能会被实例化.

所以我需要介于两者之间.如果有这样的话会很高兴:

 extern template class Foo; // suppress all implicit instantiations of Foo
Run Code Online (Sandbox Code Playgroud)

(注意缺少模板参数.)任何想法?

小智 2

我想说,你的问题的答案是使用 C++ 新类型特征来断言构造函数中的实例化:

static_assert(std::is_same<TInstantiation, [your-predefined-type]> || std::is_same<TInstantiation, [your-predefined-type2]> /*And so on...*/, "Classname can not be instantiated using this type!");
Run Code Online (Sandbox Code Playgroud)

这一切都保证在编译时解决:)