模板、类型名、lambda ->从属名称不从属?
考虑:
template < typename Something >
boost::function<void()> f()
{
typedef typename Something::what type;
return [](){};
}
在此代码中,您需要类型名称,因为“what”是从属名称。但请考虑一下:
template < typename Something >
boost::function<void()> f()
{
return []()
{
typedef typename Something::what type;
};
}
编译器婊子:“typename 不能在模板声明之外使用”
WTF?
这是有效的:
template < typename Something >
boost::function<void()> f()
{
return []()
{
typedef Something::what type;
};
}
创建 lambda 意味着“什么”不再是依赖名称,这是怎么回事?或者这只是一个错误?
呵呵……更正。后者不起作用。它说“某物”不存在。这个修改后的版本确实可以工作,但仍然不直观地不需要也不会接受“typename”。
template < typename T > struct wtf { typedef typename T::what type; };
template < typename Something >
boost::function<void()> f()
{
return []() { typedef wtf<Something>::type type; };
}
当然,现在我有两个问题:原来的,WTF 除非用作模板参数,否则它不会找到“某物”吗?
Consider:
template < typename Something >
boost::function<void()> f()
{
typedef typename Something::what type;
return [](){};
}
In this code you need the typename because 'what' is a dependent name. But consider this:
template < typename Something >
boost::function<void()> f()
{
return []()
{
typedef typename Something::what type;
};
}
Compiler bitches: "typename cannot be used outside a template declaration"
WTF?
THIS works:
template < typename Something >
boost::function<void()> f()
{
return []()
{
typedef Something::what type;
};
}
What is it about the creation of a lambda that means "what" is not a dependent name anymore? Or is this just a bug?
Heh...correction. The latter doesn't work. It says that "Something" doesn't exist. This modified version DOES work though and still unintuitively doesn't need and won't accept "typename".
template < typename T > struct wtf { typedef typename T::what type; };
template < typename Something >
boost::function<void()> f()
{
return []() { typedef wtf<Something>::type type; };
}
Of course, now I have TWO questions: the original and, WTF doesn't it find "Something" unless it's used as a template parameter??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个非常有趣的问题。根据我的理解,根据 N3225 5.1.2/7 第一个“WTF”(lambda 主体中带有
typename
的)应该是正确的:由于
Something
是 lambda 表达式上下文中的依赖名称,因此根据此引用,它也应该是 lambda 函数体上下文中的依赖名称。That's a very interesting question. From my understanding, the first 'WTF' (the one with
typename
in the lambda body) should be the correct according to N3225 5.1.2/7 :As
Something
is a dependent-name in the context of the lambda expression, it should also be a dependent name in the context of the lambda function body according to this quote.这是因为 lambda 实际上是编译器定义的类,它不共享外部函数的模板参数,lambda 类型是在实例化模板时定义的,因此模板参数不再依赖于
typename< /code> 不需要。
It's because the lambda is actually a class defined by the compiler, it doesn't share the template arguments of the outer function, the lambda type is defined when the template is instantiated so the template argument is no longer dependant and
typename
isn't needed.