gpt4 book ai didi

c++ - 如何创建通用函数,它将返回 C++ 中任何级别指针的值?

转载 作者:太空狗 更新时间:2023-10-29 23:39:22 25 4
gpt4 key购买 nike

我想要一个返回指针值的函数,无论它是什么级别的指针。就像它可以是单指针或双指针或三指针或更多,但该函数应该返回值。

示例:

#include <iostream>
using namespace std;

template <class T>
T func(T arg){
// what to do here or there is some other way to do this?????
}

int main() {
int *p, **pp, ***ppp;
p = new int(5);
pp = &p;
ppp = &pp;

cout << func(p); // should print 5
cout << func(pp); // should print 5
cout << func(ppp); // should print 5
return 0;
}

所以,现在我只想在一个函数中传递这个 p、pp、ppp,它应该打印或返回值“5”。

最佳答案

只有一个重载接受任何指针并调用自身解引用,以及一个接受任何东西的重载:

template <class T>
T func(T arg) {
return arg;
}

template <class T>
auto func(T* arg){
return func(*arg);
}

即使没有 C++11,这也是可能的,只需要编写一个类型特征来完成所有的解引用:

template <class T>
struct value_type { typedef T type; };

template <class T>
struct value_type<T*> : value_type<T> { };

template <class T>
T func(T arg) {
return arg;
}

template <class T>
typename value_type<T>::type func(T* arg){
return func(*arg);
}

关于c++ - 如何创建通用函数,它将返回 C++ 中任何级别指针的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36285211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com