gpt4 book ai didi

c++ - 函数模板的函数作用域结构的静态成员函数是否被视为依赖作用域?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:37 25 4
gpt4 key购买 nike

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 提供的相关问题:typename outside of template


这是两个编译器都满意的 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);
}

关于c++ - 函数模板的函数作用域结构的静态成员函数是否被视为依赖作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8424320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com