被视为依赖作用域的函数模板的函数作用域结构体的静态成员函数

Is a static member function of a function-scoped struct of a function template considered a dependent scope?

本文关键字:函数 作用域 结构体 静态成员 函数模板 依赖      更新时间:2023-10-16

MSVC 9和g++-4.5不同意在nested::baz中使用typename。哪个是正确的?

template<typename T>
  struct foo
{
  typedef T type;
};
template<typename T>
  typename foo<T>::type
    bar(T x)
{
  struct nested
  {
    inline static typename foo<T>::type baz(T x)
    {
      typename foo<T>::type result;
      return result;
    }
  };
  return nested::baz(x);
}
int main()
{
  int x;
  bar(x);
  return 0;
}

MSVC的输出:

$ cl test.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.
test.cpp
test.cpp(15) : error C2899: typename cannot be used outside a template declaration

g++-4.5没有错误,但是如果我删除了有问题的typename,我收到一个错误消息:

$ g++-4.5 test.cpp
test.cpp: In static member function 'static typename foo<T>::type bar(T)::nested::baz(T)':
test.cpp:15:7: error: need 'typename' before 'foo<T>::type' because 'foo<T>' is a dependent scope
test.cpp:15:20: error: expected ';' before 'result'
test.cpp:16:14: error: 'result' was not declared in this scope
test.cpp: In static member function 'static typename foo<T>::type bar(T)::nested::baz(T) [with T = int, typename foo<T>::type = int]':
test.cpp:20:23:   instantiated from 'typename foo<T>::type bar(T) [with T = int, typename foo<T>::type = int]'
test.cpp:26:8:   instantiated from here
test.cpp:15:7: error: dependent-name 'foo<T>::type' is parsed as a non-type, but instantiation yields a type
test.cpp:15:7: note: say 'typename foo<T>::type' if a type is meant

在这种情况下哪个是正确的?

MSVC似乎有错;参考上面jagansai提供的相关问题:


这是bar的一个解决方案,两个编译器都很满意:

template<typename T>
  typename foo<T>::type
    bar(T x)
{
  typedef typename foo<T>::type result_type;
  struct nested
  {
    inline static result_type baz(T x)
    {
      result_type result;
      return result;
    }
  };
  return nested::baz(x);
}