[英]How to call template member function in gdb?
I'm trying to print the return value of a templated member function in gdb (version 7.6.1 I think) of an rvalue reference, so what I write in gdb amounts to something like this:我正在尝试在右值引用的 gdb(我认为是 7.6.1 版)中打印模板化成员函数的返回值,所以我在 gdb 中编写的内容大致如下:
gdb> print (*(TypeOne*)var).get<TypeTwo>()
I've tried parenthesizing various parts of the expression with no success, and I wasnt able to find any other question on this.我尝试将表达式的各个部分括起来但没有成功,并且我找不到任何其他问题。 Anyone know?
有人知道吗?
Starting from this related post: How to `print`/evaluate c++ template functions in gdb从这篇相关文章开始: 如何在 gdb 中`打印`/评估 c++ 模板函数
I was able to figure out how to do this within my own program.我能够弄清楚如何在我自己的程序中做到这一点。 I'm not using an rvalue nor a variant so it may not work for that, but I think it's still relevant to this question.
我没有使用右值或变体,所以它可能不适用于那个,但我认为它仍然与这个问题相关。
My use case was a method with a single enum as a template parameter, similar to this:我的用例是一个将单个枚举作为模板参数的方法,类似于:
#include <stdio.h>
enum class MyEnum {
VALUE_0 = 0,
VALUE_1 = 1
};
struct TestStruct {
template <MyEnum VALUE>
int getValue() {
if constexpr (VALUE == MyEnum::VALUE_0) {
return value_0;
} else /* VALUE == MyEnum::VALUE_1 */ {
return value_1;
}
}
const int value_0 = 7;
const int value_1 = 9;
};
int main()
{
TestStruct test;
test.template getValue<MyEnum::VALUE_0>();
test.template getValue<MyEnum::VALUE_1>();
return 0;
}
If we use ptype
on the object we get a list of methods on the object:如果我们在对象上使用
ptype
,我们会得到对象上的方法列表:
(gdb) b 36
Breakpoint 1 at 0x4004f7: file main.cpp, line 36.
(gdb) r
Starting program: /home/a.out
Breakpoint 1, main () at main.cpp:36
36 return 0;
(gdb) ptype test
type = struct TestStruct {
const int value_0;
const int value_1;
public:
int getValue<(MyEnum)1>(void);
int getValue<(MyEnum)0>(void);
}
If we want to call this method:如果我们想调用这个方法:
int getValue<(MyEnum)1>(void);
We can call it by using the name exactly as shown, in single quotes.我们可以使用如图所示的名称(在单引号中)来调用它。
(gdb) p test.'getValue<(MyEnum)1>'()
$1 = 9
You can try it here: https://onlinegdb.com/7OtaUvK3g你可以在这里试试: https : //onlinegdb.com/7OtaUvK3g
Note from the other thread:另一个线程的注意事项:
Without an explicit instance in the source code, the compiler will treat the template code as it would "static inline" code and optimize it out if it is unused.
如果源代码中没有显式实例,编译器会将模板代码视为“静态内联”代码,并在未使用时对其进行优化。
So you must call the method somewhere in your code to be able to call it in gdb at all, this will not work otherwise.因此,您必须在代码中的某处调用该方法才能在 gdb 中调用它,否则这将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.