【发布时间】:2021-12-29 06:00:05
【问题描述】:
代码如下:
//template_test.h
enum SnType
{
Sa,
Sb,
Sc
};
//main.cc
#include <iostream>
#include "template_test.h"
using namespace std;
template<SnType _Tsn>
class Test
{
public:
void print()
{
cout << "Type is " << _Tsn << endl;
}
};
int main()
{
SnType type = Sa;
switch (type)
{
case Sa:
Test<Sa> A;
break;
case Sb:
Test<Sb> A;
break;
case Sc:
Test<Sc> A;
break;
default:
break;
}
A.print();
return 0;
}
当我运行代码时,终端显示错误:'A' is not declared in this scope.
如何在 switch 范围之外使用 A? 在切换范围之外,如何使用在 C++ 切换范围中定义的模板变量 非常感谢!
【问题讨论】:
-
你不能。 c++ 中的类型是静态的。您不能根据运行时值更改类型。要么你知道类型,要么使用一些类型擦除,比如
std::variant或多态类。 -
为什么要在
switch的范围之外调用A.print()?当SnType type设置为Sb而不是Sa时调用A.print()的目的是什么,因为在这种情况下A永远不会被构造? -
通常多态是解决方案。你甚至可以去掉 switch 语句,让运行时类型解析选择正确的打印版本(假设它是基本类型的虚拟成员函数)。
-
你在 switch 范围内声明一个变量然后在外面调用它,编译器不知道什么是 A 变量。我认为您应该将继承与超类和 3 个子类 A、B、C 一起使用。
-
你想用
Test<Sa>做什么?