[英]Constexpr class template member function with deduced void return type?
[英]deduced return type depedent on member function template argument
我试图弄清楚这段代码有什么问题:
#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>();
}
我正在重构一个 class,其中Func
返回类型被声明为Test
class 的模板 class 参数,但我想将其更改为成员模板参数。
这可能吗? 如果是,任何人都可以建议我正确的语法?
删除decltype
。
decltype
给出表达式的类型。 但是Foo::Deduced
已经是一个类型,所以你不能对它应用decltype
。 您只是想引用该类型本身。 所以你所要做的就是写Foo::Deduced
。
但是,在某些情况下,您需要在它前面加上typename
以告诉编译器它确实是一个类型。 在 C++20 中,您需要typename
在return Foo::Deduced()
中,但在尾随返回类型中不需要它。 在 C++20 之前,这两个地方都需要它。 因此,您的代码可以像这样重写:
template<typename Foo>
auto Func() -> Foo::Deduced
{
return typename Foo::Deduced();
}
或者可以使用推导的返回类型:
template<typename Foo>
decltype(auto) Func() // notice no trailing return type
{
return typename Foo::Deduced();
}
在这个别名声明中
using Deduced = typename std::string;
关键字typename
是多余的。 写吧
using Deduced = std::string;
模板 function Func
是 class Test
的私有成员 function 。 您需要将其公开。
decltype
说明符需要一个表达式。 你至少应该写
auto Func() -> typename Foo::Deduced
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.