JSh*_*use 11 c++ templates instantiation template-specialization
据我了解,c ++模板通过为每种所需的类型编译一个单独的类或函数来工作。对于只需要少数几种不同类型/参数调用的类或函数来说,这似乎是合乎逻辑的,但是std::array似乎这可能导致同一类被编译成数百种不同版本。
我了解std::array过C样式数组的优点,但是如果我的上述假设正确的话,使用前者似乎会产生比后者更大的二进制大小。
例如,如果说在一个大型程序中,我们最终在整个代码中使用了99个大小不同的数组,那么我们实际上就有:
int arr[1] = { ... }
int arr[2] = { ... }
int arr[...] = { ... }
int arr[99] = { ... }
int arr[100] = { ... }
Run Code Online (Sandbox Code Playgroud)
要么
std::array<int, 1> arr = { ... }
std::array<int, 2> arr = { ... }
std::array<int, ...> arr = { ... }
std::array<int, 99> arr = { ... }
std::array<int, 100> arr = { ... }
Run Code Online (Sandbox Code Playgroud)
该std::array示例是否将整个类及其所有函数编译为二进制文件99次而结束?
Yes, a new class is generated by the class template for each different set of template parameters.
But that class need not as-if exist in the runtime binary.
Most of the methods are short, and should be inlined at point of use. So they won't be emitted into the binary.
If you started taking the address of the methods and storing them, you'd start running into bloat, as you are forcing each distinct method to exist.
For example of a binary bloat generator:
template<std::size_t...Ns>
std::function<std::type_info const&()> stupid(std::size_t i, std::index_sequence<Ns...>) {
std::function<std::type_info const&()> retval;
(
((i || (retval = []()->std::type_info const&{
return typeid( std::array<int, Ns> );
})) && i--) && ...
);
return retval;
}
std::function<std::type_info const&()> stupid( std::size_t i ) {
return stupid( i, std::make_index_sequence<100>{} );
}
Run Code Online (Sandbox Code Playgroud)
this requires that the library contain rtti information for 100 different std::arrays.
But if you don't do that kind of thing, the rtti isn't needed. So it isn't injected into your binary.
And I can do the exact same thing with 100 different arrays.
template<std::size_t...Ns>
std::function<std::type_info const&()> stupid(std::size_t i, std::index_sequence<Ns...>) {
std::function<std::type_info const&()> retval;
(
((i || (retval = []()->std::type_info const&{
return typeid( int[Ns] );
})) && i--) && ...
);
return retval;
}
std::function<std::type_info const&()> stupid( std::size_t i ) {
return stupid( i, std::make_index_sequence<100>{} );
}
Run Code Online (Sandbox Code Playgroud)
a "class" in C++ isn't a heavy thing like in other OO languages. There is no global class state unless you force it to exist.