可以在对象函数上使用decltype声明成员变量吗?

Can you declare a member variable with decltype on an object function?

本文关键字:声明 decltype 成员 变量 对象 函数      更新时间:2023-10-16
struct Example
{
    boost::tokenizer<boost::char_separator<char>> tokens;
    decltype (tokens.begin()) i;
};

在Visual Studio 2013上,我得到一个编译器错误C2228: left of '。Begin '必须有class/struct/union。

这是有效的c++ 11代码,如果不是,有没有一种方法可以在不为迭代器输入长模板类型的情况下做到这一点?

我认为decltype应该工作的逻辑是编译器绝对可以看到函数签名,所以我认为你可以根据它的返回类型声明一个变量。

您的代码有效。这是一个已知的VS bug。链接的bug报告中的示例与此类似:

#include <list>
struct used {
    int bar;
};
struct wrap {
    used u;
    auto foo() -> decltype( u.bar ) { return u.bar; }   // works
    decltype( u.bar ) x;                                // error C2228
    std::list< decltype( u.bar ) > items;               // error C2228
};