SFINAE问题在创建“is_iterable” trait - 这是一个gcc的bug吗? [英] SFINAE issue in creating an "is_iterable" trait - is this a gcc bug?

查看:156
本文介绍了SFINAE问题在创建“is_iterable” trait - 这是一个gcc的bug吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码尝试(不使用c ++ 11)创建用于标识类型是否可以STL方式迭代的trait:

The following code attempts (without using c++11) to create a trait for identifying whether a type is iterable in STL fashion :

#include <iostream>
#include <vector>

template<typename C>
struct IsIterable
{
    typedef char true_type; 
    typedef long false_type; 

    template<class T> static true_type  is_beg_iterable(
        typename T::const_iterator = C().begin()); 
    template<class T> static false_type is_beg_iterable(...); 

    enum { value = sizeof(is_beg_iterable<C>()) == sizeof(true_type) }; 
};

int main() {
    std::cout << IsIterable<std::vector<int>>::value << std::endl;
}

还有 is_end_iterable 方法,为简洁起见在此省略

there's also an is_end_iterable method, omitted here for brevity

代码 与gcc 4.9.2 *(以及旧版本)失败 并且在VS2012中成功执行。我的断言是,可变参数版本将总是在重载解决方案的最后(因此应该没有歧义),所以谁在这里?

The code fails with gcc 4.9.2 *(as well as older versions) and clang and succeeds in VS2012. My assertion is that the variadic argument version would always come last in overload resolution (thus there should be no ambiguity), so who's right here?

有没有跨平台的解决方法/替代方案?

Is there a cross-platform workaround / alternative ?

我看到现在VS的新版本也拒绝了代码,所以最后一个问题变得更加重要了。 $ b

推荐答案

这只有在函数的实际参数比省略号转换更好的情况下才有效。请记住,没有参数的默认值的参数不参与重载解析。

This only works if there's an actual argument to the function which would be a better match than an ellipsis conversion. Remember that parameters with default values for which there's no argument do not participate in overload resolution.

解决方案是添加另一个参数并传递参数:

The solution is to add another parameter and pass it an argument:

template<class T> static true_type  is_beg_iterable(int,   // <- for disambiguation
    typename T::const_iterator = C().begin());

template<class T> static false_type is_beg_iterable(...); 

enum { value = sizeof(is_beg_iterable<C>(0)) == sizeof(true_type) }; 
  //                                     ^

活动示例

这篇关于SFINAE问题在创建“is_iterable” trait - 这是一个gcc的bug吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆