gpt4 book ai didi

c++17 如何编写 is_pointer_pointer 泛型 lambda?

转载 作者:行者123 更新时间:2023-11-30 05:02:28 25 4
gpt4 key购买 nike

auto is_pointer_pointer = [] ( auto arg ) -> bool {
// implementation here
}

如何实现这个通用 lambda 的方法?

使用示例:

int main ( int argc, char ** argv ) {
auto dp = is_pointer_pointer(argv) ; // returns true
}

解决方案

感谢@luk32。我已经将他的解决方案(又名“答案”)带到了魔杖盒中,并使其更具弹性。代码是 here .

解决方案是这个 lambda:

  // return true if argument given is
// pointer to pointer of it's type T
// T ** arg
auto is_pointer_pointer = [&] ( const auto & arg ) constexpr -> bool {
using arg_type = std::decay_t< decltype(arg) > ;
return std::is_pointer_v<arg_type> &&
std::is_pointer_v< std::remove_pointer_t<arg_type> > ;
};

求知若渴here这篇文章用自动参数解释了 c++17 通用 lambda 问题。提示:这就是我在上面使用 std::decay 的原因。

最佳答案

在 c++14 中使用 decltypetype_traits 工具已经成为可能。

#include <type_traits>
#include <iostream>
using namespace std;


int main() {
auto is_double_pointer = [] ( auto arg ) -> bool {
return std::is_same<decltype(arg), double*>::value;
};

auto is_pointer_pointer = [] ( auto arg ) -> bool {
return std::is_pointer<decltype(arg)>::value &&
std::is_pointer< typename std::remove_pointer<decltype(arg)>::type >::value;
};


double d, *ptrd, **ptrptrd;

std::cout << is_double_pointer(d) << '\n';
std::cout << is_double_pointer(ptrd) << '\n';
std::cout << is_double_pointer(ptrptrd) << '\n';
std::cout << is_pointer_pointer(d) << '\n';
std::cout << is_pointer_pointer(ptrd) << '\n';
std::cout << is_pointer_pointer(ptrptrd) << '\n';
return 0;
}

输出:

0
1
0
0
0
1

编辑:也适用于 char** argv;

关于c++17 如何编写 is_pointer_pointer 泛型 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49878757/

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