C ++: force compilation of a template (MSVC / g ++)

Hello, good afternoon.

Compilation of a piece of code on cl.exe (15.00.30729.01) and mingw-g ++ (4.4.0):

template<typename T> class Test{ public: T t; void error(){ int doesNotExist = 6; return doesNotExist;//<---- void function returning result } }; int main(int argc, char** argv){ Test<int> test; return 0; } 

Also, on cl.exe, you can even get away with something like this:

 template<typename T> class Test{ public: T t; void error(){ doesNotExist = 6;//<---- undeclared variable return doesNotExist;//<---- void function returning result } }; 

Now this obviously happens because the compiler does not create content for the methods of the template class until someone calls them. However, this can cause problems when developing a large class of templates (since you most likely will not want to add a test call to another method somewhere).

Question:
Is there a compiler for g ++ or cl.exe that will force the compiler to process the entire template (so this piece of code causes a compilation error)?

+6
source share
1 answer

If you want to test a template with several types, you can run manual instances of types, for example:

 // at namespace level template class Test<int>; 

Explicit instances of class templates automatically start an instance of all members, which seems to be what you want.

The real problem is that the language is intended to explicitly allow behavior that you want to avoid. When a class template is implicitly created, the compiler will only instantiate the methods that are used. The main use case for this function is that some methods may require more stringent requirements for the type of instance than others, if all methods have always been created, then the class template can only be used with those types that satisfy more stringent requirements.

By providing the compiler with only an instance of the methods that are used, the class template can be used with types that do not meet all the requirements of all methods if they meet the requirements of the methods that are actually used.

A common example is operator[] in std::map<> , for which the value_type constructor must be constructive by default ( operator[] will create a new default object, initialized if the key is not in the container and returns a reference to This). The behavior in the language allows std::map to be used for types that by default cannot be constructive unless you use operator[] (or any other member function that imposes this requirement).

+11
source

Source: https://habr.com/ru/post/900597/


All Articles