在模板实例化中使用运行时值
use a run-time value in template instantiation
请考虑类A
和函数对象A_less
。A_less
根据A::getvalue()
的结果比较两个A
指针。
class A {
int getvalue(const string &Parameter);
};
struct A_less : public binary_function<A *, A *, bool> {
A_less(const string &P) : Parameter(P) { }
bool operator()(const A *lhs, const A *rhs) const {
return A->getvalue(Parameter) < rhs->getvalue(Parameter);
}
string Parameter;
}
如何声明/创建A
指针的排序容器(集合、优先级队列…),根据Parameter
的特定(运行时)值按A_less
排序?
像这样:
std::string p = ...;
std::set<A,A_less> m(A_less(p));
您必须指定模板参数Compare
(这是set
的第二个参数)。构造映射时,需要将比较函数对象赋予map
的构造函数。
相关文章:
- 如何创建一个空的全局类并在启动时实例化它
- glfw 在创建之前/创建时实例化窗口位置
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 根据运行时参数避免模板实例化的代码重复
- 获取派生模板实例化的运行时类型
- 如何根据运行时输入实例化 c++ 模板
- JIT 编译的运行速度能否比编译时模板实例化更快?
- 使用运行时常量实例化的函数模板
- 有没有办法在编译时实例化所有 c++ 模板大小
- 我能否获得一个C++编译器在编译时实例化对象
- C++类实例化是否可以在运行时更改其大小
- 在运行时初始化 boost::accumulator_set
- 在运行时根据不同的类型实例化模板类
- 如何在定义映射/集合时实例化比较函数(函子)
- 运行时初始化 a const
- .NET程序集在运行时初始化
- 位集限制,如何在C++中运行时初始化整数
- 我可以在运行时初始化静态浮点变量吗
- 如何在构造函数接受参数时实例化模板类