我正在尝试从std :: optional中的struct成员获取类型这是成员函数的返回类型. 这是一个简化的例子: struct Result{ int tag; int pos;};class Dict{public: std::optionalResult search(const char *word) { return Resu
这是一个简化的例子:
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(const char*)->pos) position;
return 0;
}
如果您将实际参数传递给搜索,它将起作用(以及公开搜索):
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;
}
要搜索的参数不必有效(就您的函数所期望的而言 – 因为它实际上不会调用它),它只需要是正确的类型.
如果你想直接处理类型而不是实例,正如你的评论所暗示的那样,那么@ Jarod42指出你可以使用以下行作为你的变量声明:
decltype(std :: declval< Dict>().search(std :: declval< const char *>()) – > pos)position;
https://wandbox.org/permlink/kZlqKUFoIWv1m3M3
虽然我可能不需要指出~70字符变量类型是多么难以理解.我想如果是我,我会使用一个int,或者我会为pos创建一个类型别名,例如使用ResultPositionType = int;然后在Result结构中使用它,再在main中使用它.
