代碼如下:
//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' 未在此范圍內宣告。
如何使用 A out of the switch scop?在 switch 作用域之外,我如何使用 C 中 switch 作用域中定義的模板變數,非常感謝!
uj5u.com熱心網友回復:
如何在 switch 范圍之外使用 A?
你不能。它已不復存在。
旁白:所有以下劃線開頭并后跟大寫字母的名稱都是保留的,_Tsn會使您的程式格式錯誤。
你必須在 switch 中做你依賴于型別的事情,例如
#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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/366263.html
上一篇:函式模板引數推導中的編譯器差異
