使用SFINAE检测是否有(增强)范围

时间:2013-01-21 13:14:44

标签: c++ boost sfinae c++03

对于日志代码,我想检测模板函数的给定参数是否可以使用Boost.Range中的工具进行迭代。显然我需要实例化不同的代码,不管是不是,所以我需要SFINAE,可能(当然)与boost :: enable_if结合使用。我已经尝试检测是否定义了beginend自由函数,如下所示:

namespace is_range_impl {
    template <typename T> T &make();
    struct any { template <class T> any(T const&); };
    struct not_range {};
    not_range begin(const any &);
    not_range end(const any &);
    struct no_type { char x[8]; };
    typedef char yes_type;
    template <typename T> yes_type check(const T &t);
    no_type check(const not_range &t);
    using boost::begin;
    using boost::end;
    template <typename T> struct is_range_impl {
        enum e {
            value = (sizeof(check(begin(make<T>()))) == sizeof(yes_type) &&
                     sizeof(check(end(make<T>()))) == sizeof(yes_type)),
        };
    };
}

template <typename T>
struct is_range : public is_range_impl::is_range_impl<T> {};

template <typename T>
typename boost::disable_if<is_range<T> >::type repr(std::ostream &s, const T &v)
{ ... }

template <typename T>
typename boost::enable_if<is_range<T> >::type repr(std::ostream &s, const T &v)
{ ... }

但是,当boost::beginboost::end没有明确定义时,它没有默默地失败,而是因为错误而大声失败

'type' : is not a member of 'boost::mpl::eval_if_c<C,F1,F2>'
    [C=false, F1=boost::range_const_iterator<void *>, F2=boost::range_mutable_iterator<void *>]

boost/range/iterator.hpp:63中的以下代码中:

typedef BOOST_RANGE_DEDUCED_TYPENAME
        mpl::eval_if_c< is_const<C>::value,
                        range_const_iterator< typename remove_const<C>::type >,
                        range_mutable_iterator<C> >::type type;

(我有1.51提升,但1.52列出无变化,1.53 alpha列出两个错误修复,但似乎都不相关)

那么有更好的方法来检测范围吗?虽然我遇到了一些C ++ 03编译器并且可能会持续很长时间,但我希望能够轻松切换到C ++ 11(免费beginend可以通过ADL获得所有需要的东西。

具体来说,编译器是Visual C ++ 9.0和GCC 4.5。 SFINAE支持足够。

1 个答案:

答案 0 :(得分:5)

我相信你需要使用的元函数是has_range_iterator

Running on LWS

#include <iostream>
#include <string>
#include <utility>

#include <boost/range.hpp>

template <typename T>
typename boost::disable_if<boost::has_range_iterator<T> >::type repr(const T &, const std::string& name)
{ std::cout << name << " is not a range" << std::endl; }

template <typename T>
typename boost::enable_if<boost::has_range_iterator<T> >::type repr(const T &, const std::string& name)
{ std::cout << name << " is a range" << std::endl; }

struct foo{};
struct bar
{
   typedef int iterator;
    typedef const int const_iterator;
    int begin(){ return 0;};
    int end(){ return 1;};
};


int main()
{
    int i;
    repr(i, "int");
    int array[10];
    repr(array, "int array");
    std::string str;
    repr(str, "std::string");
    foo f;
    repr(f, "foo");
    bar b;
    repr(b, "bar");

    std::pair<int, int> p;
    repr(p, "pair"); // it does make a mistake here, because std::pair<int, int> looks like range, but int is not valid iterator (cannot be dereferenced)
}