缺少表达方式SFINAE的解决方法 [英] Workaround for lack of expression SFINAE

查看:101
本文介绍了缺少表达方式SFINAE的解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为 std :: tuple 中的每个值调用一个函数,当然没有办法迭代一个元组,因此我求助于使用迭代元组

I'm trying to call a function for each value in a std::tuple, of course there is no way to iterate a tuple and so I've resorted to using the template techniques discussed in iterate over tuple

但是,我使用的是Visual Studio 2013,它不支持表达式SFINAE,因此该代码将不起作用。我曾尝试根据常数(例如5、4、3、2、1、0)对模板进行部分专业化处理,但没有成功。我当然不是模板专家,所以我希望有人可以帮助我。我的表达式SFINAE代码如下。

However, I'm using Visual Studio 2013 and it does not support expression SFINAE, so that code won't work. I've tried to partially specialize the templates based on a constant numbers (e.g 5, 4, 3, 2, 1, 0), but haven't had any success. I'm certainly no template expert, and so I was hoping somebody could help me out. My expression SFINAE code is below.

#include <iostream>
#include <tuple>

using namespace std;

struct ArgPush {
    void push(bool x) {}
    void push(int x) {}
    void push(double x) {}
    void push(const char* x) {}
    void push(const std::string& x) {}

    template<std::size_t I = 0, typename... Tp>
    inline typename std::enable_if<I == sizeof...(Tp), void>::type
        push_tuple(const std::tuple<Tp...>& t)
    { }

    template<std::size_t I = 0, typename... Tp>
    inline typename std::enable_if<I < sizeof...(Tp), void>::type
        push_tuple(const std::tuple<Tp...>& t)
    {
        push(std::get<I>(t));
        push_tuple<I + 1, Tp...>(t);
    }
};

int main() {
    ArgPush().push_tuple(std::make_tuple(1,2,3,4));
    ArgPush().push_tuple(std::make_tuple("hello", "msvc makes me sad", 4, true));
    return 0;
}


推荐答案

MSVC不喜欢在 enable_if 中进行相等比较。因此,将它们从那里移到帮助器模板。然后,您的代码在VS2013上编译。

MSVC doesn't like the equality comparisons being made within the enable_if. So move these out from there to a helper template. Then your code compiles on VS2013.

template<std::size_t I, typename... Tp>
struct comparator
{
    static const bool value = (I < sizeof...(Tp));
};

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<!comparator<I, Tp...>::value>::type
    push_tuple(const std::tuple<Tp...>& t)
{ }

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<comparator<I, Tp...>::value>::type
    push_tuple(const std::tuple<Tp...>& t)
{
    push(std::get<I>(t));
    push_tuple<I + 1, Tp...>(t);
}

这篇关于缺少表达方式SFINAE的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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