[英]deduced return type depedent on member function template argument
I am trying to figure out what's wrong with this code:我试图弄清楚这段代码有什么问题:
#include <string>
struct Bar
{
using Deduced = typename std::string;
};
class Test
{
template<typename Foo>
auto Func() -> decltype(Foo::Deduced)
{
return Foo::Deduced();
}
};
int main()
{
Test t;
std::string ret = t.template Func<Bar>();
}
I am refactoring a class where Func
return type was declared as a template class parameter of Test
class, but I would like to change this to work as a member template parameter.我正在重构一个 class,其中Func
返回类型被声明为Test
class 的模板 class 参数,但我想将其更改为成员模板参数。
Is this possible?这可能吗? If yes, anyone could suggest me the right syntax?如果是,任何人都可以建议我正确的语法?
Remove the decltype
.删除decltype
。
decltype
gives the type of an expression . decltype
给出表达式的类型。 But Foo::Deduced
is already a type, so you can't apply decltype
to it.但是Foo::Deduced
已经是一个类型,所以你不能对它应用decltype
。 You simply want to refer to that type itself.您只是想引用该类型本身。 So all you have to do is write Foo::Deduced
.所以你所要做的就是写Foo::Deduced
。
However, in some contexts, you need to prefix it with typename
to tell the compiler that it's really a type.但是,在某些情况下,您需要在它前面加上typename
以告诉编译器它确实是一个类型。 In C++20, you need typename
in return Foo::Deduced()
but you don't need it in the trailing return type.在 C++20 中,您需要typename
在return Foo::Deduced()
中,但在尾随返回类型中不需要它。 Prior to C++20, it was needed in both places.在 C++20 之前,这两个地方都需要它。 Thus your code could be rewritten like so:因此,您的代码可以像这样重写:
template<typename Foo>
auto Func() -> Foo::Deduced
{
return typename Foo::Deduced();
}
Or a deduced return type could be used:或者可以使用推导的返回类型:
template<typename Foo>
decltype(auto) Func() // notice no trailing return type
{
return typename Foo::Deduced();
}
In this alias declaration在这个别名声明中
using Deduced = typename std::string;
the keyword typename
is redundant.关键字typename
是多余的。 Just write写吧
using Deduced = std::string;
The template function Func
is a private member function of the class Test
.模板 function Func
是 class Test
的私有成员 function 。 You need to make it public.您需要将其公开。
The decltype
specifier expects an expression. decltype
说明符需要一个表达式。 You should write at least like你至少应该写
auto Func() -> typename Foo::Deduced
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.