【问题标题】:How to access a template struct const variable in CPP如何在 CPP 中访问模板结构 const 变量
【发布时间】:2021-07-10 19:09:00
【问题描述】:

我正在使用一个代码,其中我将一个常量变量传递给这样的模板结构

#include <iostream>
using namespace std;



//Compiler version g++ 6.3.0

template<typename T>

struct Data {
    T age;
};

void show();

int main()
{

      Data<const int> person{
        18
      };

      cout << person.age;

     show();

}


void show(){




}

在代码中,我想在函数'show()'内部读取const变量'Tage'(Tage值为18,由main函数赋值),而不传递struct变量作为参数。

这是我尝试过的

#include <iostream>
using namespace std;



//Compiler version g++ 6.3.0

template<typename T>

struct Data {
    T age;
};

void show();

int main()
{

      Data<const int> person{
          18
      };

      cout << person.age;

      show();

}


void show(){

      Data<const int> person;

      cout << person.age;


}

错误信息

source_file.cpp: In function ‘void show()’:
source_file.cpp:32:18: error: use of deleted function ‘Data<const int>::Data()’
  Data<const int> person;
              ^~~~~~
source_file.cpp:10:12: note: ‘Data<const int>::Data()’ is implicitly deleted because the default definition would be ill-formed:
     struct Data {
            ^~~~
source_file.cpp:10:12: error: uninitialized const member in ‘struct Data<const int>’
source_file.cpp:11:8: note: ‘const int Data<const int>::age’ should be initialized
      T age;
        ^~~

那么我如何在函数“show()”中读取“T age”的值而不将 struct 变量作为参数从“int main()”传递?

非常需要更正代码和适当的解释。

【问题讨论】:

  • 您可以将person 声明为全局变量...但我强烈反对使用全局变量。或者你可以定义show(),在main()里面,作为一个lambda函数,捕获person;比如auto show = [&amp;]{ std::cout &lt;&lt; person.age; };
  • 我的建议是通过一个人显示使用参考。或者让 show 成为 Data 的成员
  • @Max66 真的很抱歉兄弟,在我的代码中,我不能使用 lambda,我只想从用户定义的函数 show() 中读取变量。
  • @drescherjm 请提供代码示例
  • T age;之后和下一个};之前放void show() { cout &lt;&lt; age; }

标签: c++ templates


【解决方案1】:

您的代码根本不起作用。 person 变量不会填充到show() 的主体中,因此在该函数中,您只需创建一个不指定值的默认结构。最后,它崩溃了。

你可以做的是:

  1. 将结构传递给函数并获取其内部变量。
  2. 在全局空间中创建一个静态结构并在您的函数中读取它。
  3. 使用 lambda。

【讨论】:

  • 一个关键点是在其他范围内将变量命名为相同的变量之间没有联系。他们不分享价值观或任何东西。
猜你喜欢
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2018-06-24
  • 2021-07-23
相关资源
最近更新 更多