Cam*_*ron 5 c++ templates default-parameters
例如,以下代码片段在 VC++ 2010 中编译:
template<int Rows, int Columns = Rows>
struct Matrix { };
Matrix<4> m;
Run Code Online (Sandbox Code Playgroud)
请注意, 的默认参数Columns取决于 的参数值Rows。
但是C++11(或更早版本)中的这种标准行为是我可以在任何地方依赖的吗?
是的。事实上,大量的 STL 代码就是这样工作的。
thestd::vector的定义如下:
template < class T, class Alloc = allocator<T> > class vector
Run Code Online (Sandbox Code Playgroud)
这样您就不需要allocator每次都指定。如果这样无效,我们将无法编写:
std::vector<int> data;
Run Code Online (Sandbox Code Playgroud)
你会写成std::map:
std::map < keyType, // map::key_type
ValType, // map::mapped_type
less<keyType>, // map::key_compare
allocator<pair<const KeyType,ValType> > // map::allocator_type
> mapping;
Run Code Online (Sandbox Code Playgroud)
这远不如:
std::map< keyType , ValType > mapping;
Run Code Online (Sandbox Code Playgroud)