Aaron Graham
Aaron Graham

Reputation: 231

How do I prevent implicit template instantiations for a specific template?

I'd like to prevent all implicit template instantiations for a specific templated class in order to prevent it from being instantiated into every translation unit.

It looks like my options are:

  1. Use -fno-implicit-templates on gcc's command line. This suppresses all implicit template instantiations, and is not what I want. I only want to prevent it for a single template.
  2. Use C++11 "extern template". But this only suppresses specific explicit instantiations. I don't want to type out an "extern template" line for every potential template parameter list this template might be instantiated with.

So I need something in-between. It would be nice to have:

 extern template class Foo; // suppress all implicit instantiations of Foo

(Note the lack of template parameter(s).) Any ideas?

Upvotes: 8

Views: 2202

Answers (3)

paladin324
paladin324

Reputation: 342

I would say that the answer to your question is using C++ new type traits to assert the instantiations in your constructor:

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!");

It's all guaranteed to resolve at compile time :)

Upvotes: 2

David Haim
David Haim

Reputation: 26476

you can use std::enable_if which does exactly this with the combination of std::is_same :

template <class T , typename = std::enable_if <!std::is_same<T,Foo>::value,T>::type >
class MyClass{
//...
};

now myClass won't be compiled for Foo type.

Upvotes: 3

ltjax
ltjax

Reputation: 15997

You can split the class like you would with a non-template class. Just put the declarations into a header and include that everywhere, and put the implementation into an .inl/.i file and include that only where you want your template to be instantiated. Alternatively, use compile time switches to do this with a single file - but you do have to separate declaration and implementation.

Upvotes: 1

Related Questions