Moz*_*zbi 1 c++ templates c++11
我有两段看似相似的代码,我想利用模板来防止复制的代码.
if(!myVector.empty()) {
for(auto& i : myVector)
{
std::cout << i << std::endl;
//some other code that is similar to below
}
}
if(!myUnorederedMap.empty()) {
for(auto i : myUnorderedMap)
{
std::cout << i.second << std::endl;
//some other code that is similar to top
}
}
Run Code Online (Sandbox Code Playgroud)
当我必须在地图上调用.second而不是我的向量时,如何为迭代器编写函数模板?
template <typename T>
T const& getValue(T const& t)
{
return t;
}
template <typename T, typename U>
U const& getValue(std::pair<T, U> const& p)
{
return p.second;
}
template <typename Container>
void foo(Container const& container)
{
if(!container.empty()) {
for(const auto& i : container)
{
std::cout << getValue(i) << std::endl;
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然,这条线if(!container.empty())似乎没有任何用途.你也可以写:
template <typename Container>
void foo(Container const& container)
{
for(const auto& i : container)
{
std::cout << getValue(i) << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |