Rly*_*yeh 3 c++ decltype optional
我正在尝试从std :: optional <>中的struct成员获取类型,这是成员函数的返回类型.
这是一个简化的例子:
struct Result
{
int tag;
int pos;
};
class Dict
{
public:
std::optional<Result> search(const char *word)
{
return Result{ 1,2 };
}
};
Run Code Online (Sandbox Code Playgroud)
我希望能够做到这样的事情:
int main()
{
Dict abc;
decltype(abc.search(const char*)->pos) position;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果您传递一个实际参数search,它将工作(以及search公开):
https://wandbox.org/permlink/0Q3mLW7SmQW4QshE
#include <optional>
struct Result
{
int tag;
int pos;
};
class Dict
{
public:
std::optional<Result> search(const char *word)
{
return Result{ 1,2 };
}
};
int main()
{
Dict abc;
decltype(abc.search("")->pos) position;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
参数search不必有效(就你的函数所期望的而言 - 因为它实际上不会调用它),它只需要是正确的类型.
如果你想直接处理类型而不是实例,正如你的评论所暗示的那样,那么@ Jarod42指出你可以使用以下行作为你的变量声明:
decltype(std::declval<Dict>().search(std::declval<const char*>())->pos) position;
https://wandbox.org/permlink/kZlqKUFoIWv1m3M3
虽然我可能不需要指出~70字符变量类型是多么难以理解.我想如果是我,我会使用一个int,或者我会创建一个类型别名pos,例如using ResultPositionType = int;然后在你的Result结构中使用它,再次使用main.