根据成员函数模板参数推导出返回类型depedent

deduced return type depedent on member function template argument

本文关键字:返回类型 depedent 参数 成员 函数模板      更新时间:2024-09-30

我正在努力找出这个代码的问题:

#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>();
}

我正在重构一个类,其中Func返回类型被声明为Test类的模板类参数,但我希望将其更改为成员模板参数。

这可能吗?如果是,有人能给我建议正确的语法吗?

移除decltype

decltype给出了表达式的类型。但是Foo::Deduced已经是一个类型,所以你不能将decltype应用于它。你只想引用那个类型本身。所以你所要做的就是编写Foo::Deduced

然而,在某些上下文中,您需要在它前面加上typename,以告诉编译器它实际上是一种类型。在C++20中,return Foo::Deduced()中需要typename,但尾部返回类型中不需要它。在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;

关键字CCD_ 11是多余的。只需写入

using Deduced = std::string;

模板函数CCD_ 12是类CCD_。你需要公开它。

decltype说明符需要一个表达式。你至少应该像一样写作

auto Func() ->  typename Foo::Deduced