【问题标题】:GCC ICE -- alternative function syntax, variadic templates and tuplesGCC ICE——替代函数语法、可变参数模板和元组
【发布时间】:2011-02-19 03:47:59
【问题描述】:

(与C++0x, How do I expand a tuple into variadic template function arguments?有关。)

以下代码(见下文)取自discussion。目标是将函数应用于元组。我简化了模板参数并修改了代码以允许泛型类型的返回值。

虽然原始代码编译良好,但当我尝试使用 GCC 4.4.3 编译修改后的代码时,

g++ -std=c++0x main.cc -o main

GCC 报告内部编译器错误 (ICE),并带有以下消息:

main.cc:在函数“int main()”中:
main.cc:53:内部编译器错误:在 tsubst_copy 中,位于 cp/pt.c:10077
请提交完整的错误报告,
如果合适,使用预处理的源。
有关说明,请参阅

问题:代码是否正确?还是非法代码触发了ICE?

// file: main.cc
#include <tuple>

// Recursive case
template<unsigned int N>
struct Apply_aux
{
  template<typename F, typename T, typename... X>
  static auto apply(F f, const T& t, X... x)
    -> decltype(Apply_aux<N-1>::apply(f, t, std::get<N-1>(t), x...))
  {
    return Apply_aux<N-1>::apply(f, t, std::get<N-1>(t), x...);
  }
};

// Terminal case
template<>
struct Apply_aux<0>
{
  template<typename F, typename T, typename... X>
  static auto apply(F f, const T&, X... x) -> decltype(f(x...))
  {
    return f(x...);
  }
};

// Actual apply function
template<typename F, typename T>
auto apply(F f, const T& t)
  -> decltype(Apply_aux<std::tuple_size<T>::value>::apply(f, t))
{
  return Apply_aux<std::tuple_size<T>::value>::apply(f, t);
}

// Testing
#include <string>
#include <iostream>

int f(int p1, double p2, std::string p3)
{
  std::cout << "int=" << p1 << ", double=" << p2 << ", string=" << p3 << std::endl;
  return 1;
}

int g(int p1, std::string p2)
{
  std::cout << "int=" << p1 << ", string=" << p2 << std::endl;
  return 2;
}

int main()
{
  std::tuple<int, double, char const*> tup(1, 2.0, "xxx");
  std::cout << apply(f, tup) << std::endl;
  std::cout << apply(g, std::make_tuple(4, "yyy")) << std::endl;
}

备注:如果我在递归情况下硬编码返回类型(见代码),那么一切都很好。也就是说,用这个 sn-p 代替递归情况不会触发 ICE:

// Recursive case (hardcoded return type)
template<unsigned int N>
struct Apply_aux
{
  template<typename F, typename T, typename... X>
  static int apply(F f, const T& t, X... x)
  {
    return Apply_aux<N-1>::apply(f, t, std::get<N-1>(t), x...);
  }
};

唉,这是对原始问题的不完整解决方案。

【问题讨论】:

标签: c++ gcc c++11


【解决方案1】:

我在 g++4.6 上试过你的代码。由于缺少实现,它无法编译。但是,实现通用性的一种方法是将独立函数包装在 std::function 包装器中并使用result_type typedef,如下所示。

template<typename F, typename T>
typename F::result_type apply(F f, const T& t)
{
  ...
}
int f(int p1, double p2, std::string p3) 
{
  std::cout << "int=" << p1 << ", double=" << p2 << ", string=" << p3 << std::endl;
  return 1;
}
int main()
{
  std::tuple<int, double, char const*> tup(1, 2.0, "xxx");
  std::function<int (int, double, char const *)> func = &f; 
  std::cout << apply(func, tup) << std::endl;

}

【讨论】:

  • 优雅的解决方案。不幸的是,我无法让它在 GCC 4.4.3 中工作。我不确定为什么。如果我发现任何新内容,我会在这里发布。干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2012-01-20
  • 1970-01-01
  • 2016-09-20
  • 2015-07-07
相关资源
最近更新 更多