【问题标题】:template backward compatibility with gcc 4.7模板向后兼容 gcc 4.7
【发布时间】:2013-07-10 21:14:28
【问题描述】:

取如下代码sn-p:

struct whatever {};

template < template <typename, typename> class FOX, typename bat>
struct wulf {};

template <typename A, typename B, typename C = whatever>
struct box;

template <typename A, typename B>
struct box<A, B, whatever> {};

template <typename A, typename B, typename C>
struct box : wulf<box, C> {};

int main(void)
{
return 0;
}

在 gcc 4.1.2 下编译正常,但在 gcc 4.7.2 下编译时出现以下错误:

main.cpp:14:25 error: type/value mismatch at argument 1 in template parameter list for 'template<template<class,class> class FOX, class bat> struct wulf'
main.cpp:14:25 error: expected a template of type 'template<class, class> FOX', got 'template<class A, class B, class C> struct box'

这是最小的示例代码 sn-p,我似乎能够重现此错误,但我不知道发生了什么。为什么代码被拒绝,是否有正确的方法可以在两者下编译?

【问题讨论】:

  • 无论如何,该代码不应该在 gcc 4.1 中编译...box 是一个具有 3 个类型参数的模板,它与 wulf 的第一个参数不匹配,该模板恰好是 2论据。模板模板参数通常很棘手。

标签: c++ templates c++11 gcc4 gcc4.7


【解决方案1】:

您的wulf 类模板接受一个接受两个类型参数的类模板作为其第一个模板模板参数。

在这里,您尝试提供一个接受 三个 类型参数的类模板 (box) 作为相应的参数:

template <typename A, typename B, typename C>
struct box : wulf<box, C> {};
//                ^^^

这是非法的。是否为box 类模板的第三个类型参数指定默认类型参数无关紧要:模板参数的类型和数量必须完全匹配。

要解决此问题,请更改 wulf 类模板的定义,如下所示:

template < template <typename, typename, typename> class FOX, typename bat>
//                                       ^^^^^^^^
struct wulf {};

这是一个live example,显示您的代码使用上述修复程序进行编译。

【讨论】:

  • 这是有道理的,就像大卫在上面指出的那样。我很好奇的是为什么这似乎可以用 gcc 4.1 编译
  • @PalaceChan:我会说这是 gcc 4.1 中的一个错误
  • @PalaceChan:这能回答你的问题吗? :)
【解决方案2】:

使用C++11,可以将wulf改成:

template < template <typename...> class FOX, typename bat>
struct wulf {};

虽然 GCC 4.1 不会接受它,但我担心......


我有时使用的另一个技巧:为box 添加一个包装类:

struct whatever {};

template < template <typename,typename> class FOX, typename bat>
struct wulf {};

template <typename A, typename B, typename C = whatever>
struct box;

template <typename A, typename B>
struct box<A, B, whatever> {};

template <typename A, typename B>
struct box2 : box<A, B> {};

template <typename A, typename B, typename C>
struct box : wulf<box2, C> {};

int main(void)
{
    return 0;
}

我不知道这(在 wulf 中丢失 box 的第三个参数)是否对您来说是个问题,但我过去有一些用例,这种技术有所帮助。

【讨论】:

  • 是的,我想过这个......但 4.1 不会接受这个
  • 啊,谢谢。是的,我想当我找到它时我会发布我最终做了什么(我现在不能)
猜你喜欢
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
  • 2012-03-13
  • 2013-03-23
  • 1970-01-01
相关资源
最近更新 更多