如何使用"is_member_function_pointer"在算法中包含/排除成员函数调用
How to use `is_member_function_pointer` to include/exclude member function calls in algorithms?
我正试图在算法中使用is_member_function_pointer,要么调用某个类型的特定成员函数(如果存在),要么什么都不做:
template< class T >
struct is_member_function_pointer;
检查T是否是非静态成员函数指针。如果T是非静态成员函数指针类型,则提供等于true的成员常数值。否则,值等于false。
例如:
#include <iostream>
#include <type_traits>
#include <vector>
struct A
{
void boo() const { std::cout << "boo." << std::endl; }
};
struct B {};
template<bool> struct booable;
template<>
struct booable<true> {
template<typename Type>
static void booIt(Type const & t)
{
t.boo();
}
};
template<>
struct booable<false> {
template<typename Type>
static void booIt(Type const & t)
{
std::cout << "booing a non-booable type" << std::endl;
}
};
template<typename Type>
void alg(Type const& t)
{
booable<std::is_member_function_pointer<decltype(&Type::boo)>::value>::booIt(t);
}
int main(int argc, const char *argv[])
{
A a;
B b;
alg(a);
alg(b);
return 0;
}
结构A
是布尔值,而B
不是。在算法alg
中,根据Type
是否实现成员函数boo
的事实,is_member_function_pointer
布尔值被设置为false
或true
。然后,该布尔值用于专门化booable
结构,该结构实现booIt
静态成员函数,其唯一目的是在布尔对象上调用boo
,或者不执行任何操作并通知用户。
但是,编译它(保存在main.cpp
中)会导致以下编译时错误:
main.cpp: In instantiation of ‘void alg(const Type&) [with Type = B]’:
main.cpp:46:10: required from here
main.cpp:37:54: error: ‘boo’ is not a member of ‘B’
booable<std::is_member_function_pointer<decltype(&Type::boo)>::value>::booIt(t);
这让我想知道:将这个报告为可用的布尔值而不是编译时错误难道不是这个特征结构的意义吗?这和我简单地做会得到的错误是一样的
B b;
b.boo();
我在这里做错了什么?
将其报告为可用的布尔值而不是编译时错误不是这个特征结构的重点吗?
是的,但为了测试类的某个成员,该成员需要存在。
您会得到错误,因为B
没有boo
,实例化alg
会导致decltype(&B::boo)
。你不会期望decltype(&int::foo)
编译,是吗?
你需要的是一个检查成员是否存在的特征。参见
- 是否可以编写一个C++模板来检查函数的存在
- 检查类是否具有给定签名的成员函数
例如。
您可以使用检查的结果来专门化进行进一步测试的模板。
编辑:
以下是使用表达式SFINAE:检查boo
的简单方法
template<typename T>
constexpr auto is_booable(int) -> decltype(std::declval<T>().boo(), bool())
{
return true;
}
template<typename T>
constexpr bool is_booable(...)
{
return false;
}
用法:
booable< is_booable<Type>(0) >::booIt(t);
以及现场示例。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 编译包含字符串的代码时遇到问题
- c++库的公共头文件中应该包含什么
- 将包含C样式数组的对象初始化为成员变量(C++)
- 是否需要删除包含对象的"pair"?
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 使用mongocxx驱动程序时包含头文件问题
- 如何在h文件中包含.o对象文件
- 在混合代码库中将C转换为C++时出现许多包含错误
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- cmath抛出错误C2062、C2059、C2143和C2447.cmath包含在矢量文件中
- 为什么您需要C++头文件的包含保护
- 无法在UE4中包含BP类到CPP类
- g++ 说函数不存在,即使包含正确的标头
- 在C++代码中包含opencv时,使用ctypes创建.so文件
- Visual C++GC接口如何启用它以及要包含哪个库
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 我必须安装"libbitcoin-server"才能包含"bitcoin.hpp"