绑定类型别名
std::bind with type alias
我试图使用std::transform
将map
的值复制到vector
。听了这个回答,我设法去做了。在寻找方法的过程中,我了解到了select2nd
。因此,我试图使用std::bind
实现"select2 -like"操作。但是,当定义select2nd
别名时,我得到:
test.cpp:9:19: error: expected type-specifier
using select2nd = std::bind(&T::value_type::second, std::placeholders::_1);
^
test.cpp: In function ‘int main()’:
test.cpp:29:64: error: ‘select2nd’ was not declared in this scope
std::transform(m.begin(), m.end(), std::back_inserter(v2), select2nd);
这是我想出来的代码片段:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <functional>
#include <map>
#include <vector>
template <typename T>
using select2nd = std::bind(&T::value_type::second, std::placeholders::_1);
using std::placeholders::_1;
void printn(int i) {
std::cout << i << " ";
}
int main() {
std::map<int, int> m;
std::vector<int> v1, v2;
for (auto &i : { 0, 1, 2, 3, 4 }) {
m[i] = rand();
}
// Works
std::transform(m.begin(), m.end(), std::back_inserter(v1),
std::bind(&std::map<int, int>::value_type::second, _1));
// Doesn't
std::transform(m.begin(), m.end(), std::back_inserter(v2), select2nd);
std::for_each(v1.begin(), v1.end(), std::bind(printn, _1));
std::cout << std::endl;
std::for_each(v2.begin(), v2.end(), std::bind(printn, _1));
std::cout << std::endl;
return 0;
}
为什么第一个transform
可以工作,而第二个不行?如何将别名参数化为std::bind
?
这应该可以工作,但不是更好:
template <typename T>
decltype(std::bind(&T::value_type::second, std::placeholders::_1)) select2nd(T m) {
return std::bind(&T::value_type::second, std::placeholders::_1);
}
// ....
std::transform(m.begin(), m.end(), std::back_inserter(v2), select2nd(m));
// ....
下面是另一个不需要参数的选择:
template <typename T>
decltype(std::bind(&T::value_type::second, std::placeholders::_1)) select2nd() {
return std::bind(&T::value_type::second, std::placeholders::_1);
}
你可以这样使用:
std::transform(m.begin(), m.end(), std::back_inserter(v2),
select2nd<std::map<int, int>>());
或:
std::transform(m.begin(), m.end(), std::back_inserter(v2),
select2nd<decltype(m)>());
相关文章:
- 继承模板类中的类型别名
- 为什么 GCC 在使用类型别名时处理 const reinterpret_cast不同?
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- C++模板/别名 - 模板参数列表中参数 1 处的类型/值不匹配
- 如何使用类型别名从模板化类中隐藏模板列表
- 如何检测类型类型别名?
- C++类型别名,其中值被替换
- 在Qt中注册自定义元类型的别名类型
- 使用外部定义的模板类型作为模板参数的更通用模板的模板别名
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- 通过类型别名从构造函数转发模板推导
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 为什么此模板定义了一组匹配void的别名类型
- 如何返回类中别名类型的值
- 在不键入别名类型的完整声明的情况下,无法从类模板定义中访问类型的类型别名
- 依赖于参数的查找在来自另一个命名空间的别名类型上意外行为
- 为什么我不能用"unsigned"限定别名类型?
- 当涉及到友谊时,为什么别名模板会与别名类型模板区别对待
- size_t是否保证是整数类型之一的别名类型?
- 将别名模板强制转换为别名类型