如何扩展 integer_sequence? [英] How do I expand integer_sequence?

查看:55
本文介绍了如何扩展 integer_sequence?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的函数:

I have a function which looks like this:

template <typename T, std::size_t... I>
std::ostream& vector_insert(std::ostream& lhs, const char* delim, const T& rhs, std::index_sequence<I...>) {
    std::ostream_iterator<float> it(lhs, delim);

    ((*it++ = at(rhs, I)), ...);
    return lhs;
}

这是我的最后一次尝试,但在扩展 integer_sequence 我希望有人能告诉我如何写一行可以有效扩展到:

This is my final attempt and I'm still failing on my expansion of the integer_sequence I'm hoping someone can tell me how to write a line that will effectively expand to:

*it++ = at(rhs, 0U), *it++ = at(rhs, 1U), *it++ = at(rhs, 2U)

我尝试过的其他事情是:

Other things I've tried are:

  1. *it++ = at(rhs, I...)
  2. *it++ = at(rhs, I)...
  3. (*i​​t++ = at(rhs, I))...

他们都给我错误:

错误 C3520:I:必须在此上下文中扩展参数包

error C3520: I: parameter pack must be expanded in this context

我如何扩展这个东西?

@AndyG 指出这似乎是一个 错误.

推荐答案

这似乎是 Visual C++ 的编译器错误.除了简化扩展参数包的表达式之外,我不知道有任何简单的修复方法.转换为递归方法似乎可以可靠地解决该问题.例如:

This seems like a compiler bug with Visual C++. I'm not aware of any easy fix for it other than simplifying the expression in which the parameter pack is expanded. Converting to a recursive approach seems to reliably work around the problem. For example :

#include <array>
#include <iostream>
#include <iterator>

template <typename T>
const auto& at(const T& v, size_t i) { return v[i]; }

// End of recursion
template<class T>
void vector_insert_impl(std::ostream_iterator<int> &, const char*, const T&)
{}

// Recursion case
template<class T, std::size_t N, std::size_t... I>
void vector_insert_impl(std::ostream_iterator<int> & iter, const char* delim, const T&rhs)
{
    *iter++ = at(rhs, N);

    // Continue the recursion
    vector_insert_impl<T, I...>(iter, delim, rhs);
}

template <typename T, std::size_t... I>
std::ostream& vector_insert(std::ostream& lhs, const char* delim, const T& rhs, std::index_sequence<I...>) 
{
    std::ostream_iterator<int> it(lhs, delim);

    // Call the recursive implementation instead
    vector_insert_impl<T, I...>(it, delim, rhs);

    return lhs;
}

int main() {
    std::array<int, 5> v = { 1, 2, 3, 4, 5 };
    vector_insert(std::cout, " ", v, std::make_index_sequence<v.size()>());
}

这里,参数包I只是在提供VC++没有问题的模板参数的上下文中进行了扩展.

Here, the parameter pack I is only expanded in the context of providing template parameters which VC++ has no trouble with.

这篇关于如何扩展 integer_sequence?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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