模板类型的c++运行时决策
C++ runtime decision for a template type
template<typename T>
class A
{ std::vector<T> v;
.... //other variables
void op1();
void op2();
... //other operations
};
int main()
{
string type;
cout<<"which type do you need?"
cin>>type;
if(type=="int")
A<int> ai;
else A<float> af;
return 0;
}
在两个块中,我必须执行相同的指令流。例如:
ai.op1();
ai.op2();
...
如果它们只有两个,我可以写两次,但这是一个有很多条件的可怕的解决方案。是否有一种方法可以在"if-else"之后为选定的类型执行此操作?我不能说会选哪一种?我该怎么办?
可以使用函数模板:
template <typename T>
void do_stuff()
{
A<T> ai;
ai.op1();
ai.op2();
}
然后int main()
{
std::string type;
std::cout << "which type do you need?"
std::cin >> type;
type == "int" ? do_stuff<int>() : do_stuff<float>();
}
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 我在c++代码中生成了一个运行时#3异常
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 建议在运行时将带有类实例的列表从c++导入qml
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 如何在GTK程序运行时禁用屏幕保护程序/电源管理/屏幕消隐
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 读取文件时运行时的未知行为
- 函数在Windows或Linux上运行时表现不同
- 在声明中合并两个常量"std::set"(不是在运行时)
- AWS Lambda C++运行时权限被拒绝
- 根据运行时决策组合不同的迭代器
- 模板类型的c++运行时决策