【发布时间】:2012-02-15 10:06:48
【问题描述】:
我需要获取实例化模板时提供的类型。考虑以下示例:
template <typename T> struct Foo
{
typedef T TUnderlying;
};
static Foo<int> FooInt;
class Bar
{
public:
auto Automatic() -> decltype(FooInt)::TUnderlying
{
return decltype(FooInt)::TUnderlying();
}
};
int main()
{
Bar bar;
auto v = bar.Automatic();
return 0;
}
此代码的问题是与 decltype 一起使用范围运算符。 Visual C++ 2010 抱怨如下:
错误 C2039:“TUnderlying”:不是“全局命名空间”的成员
我在 Wikipedia 上收集了有关该主题的一些信息:
在评论正式的 C++0x 委员会草案时,日本 ISO 成员团体指出“范围运算符 (::) 不能应用于 decltype,但它应该是。在这种情况下将很有用从实例中获取成员类型(嵌套类型)如下“:[16]
vector<int> v;
decltype(v)::value_type i = 0; // int i = 0;
David Vandevoorde 解决了这个问题和类似问题,并于 2010 年 3 月投票加入了工作文件。
所以我认为 Visual C++ 2010 没有实现此功能。我想出了这个解决方法:
template <typename T> struct ScopeOperatorWorkaroundWrapper
{
typedef typename T::TUnderlying TTypedeffedUnderlying;
};
auto Automatic() -> ScopeOperatorWorkaroundWrapper<decltype(FooInt)>::TTypedeffedUnderlying
{
return ScopeOperatorWorkaroundWrapper<decltype(FooInt)>::TTypedeffedUnderlying();
}
我是否错过了更优雅、更简洁的解决方案?
【问题讨论】:
-
你试过
FooInt::TUnderlying而不是decltype(FooInt)::TUnderlying吗?我看不到您希望通过decltype获得什么。 -
你添加的只是
ScopeOperatorWorkaroundWrapper<>,我不知道你想要多少“不那么冗长”。毕竟,它是一种解决方法。
标签: c++ scope c++11 operator-keyword decltype