4

考虑这段代码:

template<typename T>
struct Foo
{
    typedef T t_type;
};

template<typename T>
struct Bar
{
    typedef T t_type; 
};

template<typename U>
auto f() -> typename U::t_type::t_type
{
    return typename U::t_type::t_type();
}

int main(int, char**)
{
    typedef Foo<Bar<int>> Baz;
    f<Baz>();
}

它不能在 VS2012 下编译:

'U::t_type::{ctor} f(void)' 的显式模板参数无效

看起来,编译器得出的结论是,第二个t_typetypename U::t_type::t_type命名构造函数而不是同名嵌套类型。我能做些什么来帮助澄清情况吗?

4

2 回答 2

1

我认为这在 2012 年不受支持,但是:

template<class T>
using t_type=typename T::t_type;

template<typename U>
t_type<t_type<U>> f() {
  return {};
}

对于 2012 年,我们可以试试这个:

template<class T, size_t recurse>
struct r_type:
  r_type<typename T::t_type, recurse-1>
{};
template<class T>
struct r_type<T, 0> {
  typedef typename T::t_type t_type;
};

...

template<typename U>
auto f() -> typename r_type<U,1>::t_type {
  return {};
}

其中r_type代表“递归类型”。

于 2014-10-24T13:21:11.277 回答
1

首先,您缺少一个typename关键字

template<typename U>
auto f() -> typename U::t_type::t_type
{
    return typename U::t_type::t_type();
}

和 main 应该有论点(int,char**)

那说..

已经被报告并且显然已修复[将/已经]以未指定的“未来版本”发布)。MSVC 2013 更新 4 也受到影响。

建议的解决方法是:

template<typename T>
struct Foo
{
    typedef T t_type;
};

template<typename T>
struct Bar
{
    typedef T t_type;
};

template<typename U>
auto f() -> typename U::t_type::template t_type
                                ^^^^^^^^
{
    return typename U::t_type::t_type();
}

int main(int, char**)
{
    typedef Foo<Bar<int>> Baz;
    f<Baz>();
}

尽管如果您使用上面的代码,一切都会如下图所示:

在此处输入图像描述

于 2014-10-24T13:55:02.353 回答