C++17 如何编写is_pointer_pointer泛型 lambda
c++17 how to write is_pointer_pointer generic lambda?
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。他的解决方案(又名"答案"(我已经拿走了魔杖盒,并使其更具弹性。代码在这里。
解决方案是这个 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> > ;
};
对于知识的渴求,这里有一篇文章解释了 c++17 通用 lambda 与自动参数的问题。 提示:这就是为什么我在上面使用 std::d ecay。
在 c++14 中使用 decltype
和 type_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;
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 可组合的lambda/std::函数与std::可选
- C++ - "!pointer"和"pointer == nullptr"的区别?
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 如何将lambda作为模板类的成员函数参数
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 在 lambda 捕获中声明的变量的类型推导
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 模板函数指针和lambda
- 两组使用lambda函数的大括号
- 使lambda不可复制/不可移动
- FLTK:按下哪个按钮 - 将数字传递给按钮的回调 (lambda)
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 将带有unique_ptr的可变 lambda 传递给 const&std::function
- AWS Lambda C++运行时权限被拒绝
- 捕获lambda中的std::数组
- 这 4 个 lambda 表达式之间有什么区别?
- 为什么隐式"lambda to function pointer conversion"禁止"by reference"捕获静态成员?