The code is as follows:
//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;
}
when I run code , then the terminal shows the error: 'A' was not declared in this scope.
How can I use A out of the switch scop? Out of the switch scope, how can I use the template variable which is defined in switch scope in C Thanks a lot!
CodePudding user response:
How can I use A out of the switch scope?
You can't. It has ceased to exist.
Aside: All names that start with and underscore and are followed by a capital letter are reserved, _Tsn
makes your program is ill-formed.
You'll have to do your type-dependant things within the switch, e.g.
#include <iostream>
enum SnType
{
Sa,
Sb,
Sc
};
template<SnType Tsn>
class Test
{
public:
void print()
{
std::cout << "Type is " << Tsn << std::endl;
}
};
template<SnType Tsn>
void testPrint()
{
Test<Tsn>{}.print();
}
int main()
{
SnType type = Sa;
switch (type)
{
case Sa:
testPrint<Sa>();
break;
case Sb:
testPrint<Sb>();
break;
case Sc:
testPrint<Sc>();
break;
default:
break;
}
return 0;
}