【问题标题】:Out of the switch scope, how can I use the template variable which is defined in switch scope in C++在切换范围之外,如何使用在 C++ 切换范围中定义的模板变量
【发布时间】: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&lt;Sa&gt; 做什么?

标签: c++ templates


【解决方案1】:

如何在 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2021-08-18
    • 2022-01-05
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多