检查函数签名,也检查继承函数
Check for function signature also for inherited functions
我需要检查,如果一个容器擦除函数返回迭代器。我通常会通过例如boost来检查函数签名。但是在boost类(例如flat_set)的情况下,erase是继承的,因此不会被检查找到。但我真的很需要它。SFINAE检查继承的成员函数只显示了一个我还不能使用的c++ 11解决方案。
我试过这样做:
template <typename T>
class has_member_func_erase_it_constit
{
typedef typename T::iterator iterator;
typedef typename T::const_iterator const_iterator;
typedef BOOST_TYPEOF_TPL(&T::erase) eraseType;
typedef typename boost::function_types::result_type<eraseType>::type result;
public:
static const bool value = boost::is_same<iterator, result>::value;
};
template<class T>
struct EraseReturnsIterator
{
static CONSTEXPR bool value = has_member_func_erase_it_constit<T>::value;
};
但是它失败了,因为erase被重载了。我可能需要decltype或类似的东西来检查编译时调用const_iterator的erase的返回类型,但是我找不到。
这在c++ 11之前是如何实现的?
如果有一个erase函数返回void,这也不起作用:
template <typename T>
class has_member_func_erase_it
{
typedef typename T::iterator iterator;
typedef typename T::const_iterator const_iterator;
typedef char yes[1];
typedef char no [2];
static T makeT();
static iterator makeIt();
typedef BOOST_TYPEOF_TPL(makeT().erase(makeIt())) result;
public:
static const bool value = boost::is_same<iterator, result>::value;
};
以下作品:
/// "Stores a type"
template<typename T> struct Type2Type{
typedef T type;
};
/// Evil hackery to put an expression into a type
template<typename T>
Type2Type<T> operator,(T, Type2Type<void>);
template<typename T>
T declval();
template<class T>
struct EraseReturnsIterator
{
typedef typename T::iterator iterator;
typedef BOOST_TYPEOF_TPL((declval<T>().erase(declval<iterator>()), Type2Type<void>())) result;
static CONSTEXPR bool value = boost::is_same<iterator, typename result::type>::value;
};
基本上,我们只需调用需要其返回类型的函数。如果这种类型的函数没有返回void,那么BOOST_TYPEOF_TPL应该已经工作了。不幸的是,erase会返回void,这会破坏实现,因为它试图将"void&"传递到堆栈的某个地方。
因此,为了避免void(没有双关语的意思),我们把它放在一个类型中,该类型保存一个类型。为了能够对表达式执行此操作,我们重载了逗号操作符。这样,结果就等于"Type2Type",我们可以很容易地读取。完成了!
关于逗号过载的想法:https://stackoverflow.com/a/5553460/1930508
相关文章:
- 检查函数返回类型是否与STL容器类型值相同
- 如何检查函数是否在LLVM Instrumentation pass的ModulePass的系统头文件中定义?
- 何时在类中检查函数的定义?
- 素数检查 C++ 函数输出非素数的数字
- 如何检查函数是否真的获得了定义为 const 的变量?
- 检查函数是否可调用
- 如何检查函数是在C++单元测试中的析构函数中调用的
- 使用 SFINAE 检查函数 std::to_string 是否存在类型
- 如何检查函数模板是否专用?
- 如何检查函数中的模板参数是否与给定类型别名的专用化匹配
- 如何检查函数中不同变量的大小
- C++如何检查函数是否接收到无符号int
- 使用模板递归检查函数方法是否存在
- 如何在Visual studio C++中检查函数运行时间
- 检查函数是否单调
- 如何检查函数是否在编译时在全局范围内声明
- 检查函数是否被调用
- Boost.Hana:如何检查函数是否具有特定类型的专用性
- 如何检查函数参数是否恒定
- C++ 编译时检查函数参数