检查函数签名,也检查继承函数

Check for function signature also for inherited functions

本文关键字:检查 函数 继承      更新时间:2023-10-16

我需要检查,如果一个容器擦除函数返回迭代器。我通常会通过例如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