使用在 class 内返回 auto 的静态 constexpr 成员函数

use of a static constexpr member function returning auto inside class

我正在尝试解决我在 MSVC 2015 中遇到的一个错误(请参阅以下问题: ).

所以我想出了这个:

#include<Windows.h>

namespace wreg {

using t_oshandle     = HKEY;

struct t_api
{
    static constexpr 
    auto fnc_open_key ()     { return ::RegOpenKeyExA; }

    //this doesn't compile :
    static constexpr auto open_key   = fnc_open_key();

    //these don't compile either:
    //static constexpr decltype(fnc_open_key()) open_key     = fnc_open_key();
    //static constexpr decltype(::RegOpenKeyExA) open_key    = fnc_open_key();
};

//this does compiles and runs :
constexpr auto open_key  = t_api::fnc_open_key();

} // namespace wreg


//int main( int argc ,_TCHAR* argv[] );
{
    auto     hk = wreg::t_oshandle{};
    auto     res = wreg::t_api::open_key( HKEY_LOCAL_MACHINE ,"SOFTWARE" ,0 ,KEY_READ ,&hk );
    //auto   res = wreg::open_key( HKEY_LOCAL_MACHINE ,"SOFTWARE" ,0 ,KEY_READ ,&hk );

    if (res == ERROR_SUCCESS)
    {
        res = ::RegCloseKey( hk );
    }
    return 0;
}

但由于

而无法编译

error C3779: 'wreg::t_api::fnc_open_key': returns 'auto' 在定义之前不能使用的函数

我不明白。 它在我使用它的时候被明确定义了。 除此之外,在 class 通常 中 class 定义的本地名称可以在其 definition/declaration.

之前使用

问题:为什么 MSVC 是正确的或者我的代码应该编译?

您可以尝试在自动函数推导上使用 decltype:

auto fnc_open_key () -> decltype(::RegOpenKeyExA) {
       return ::RegOpenKeyExA;
}

这不再是问题。错误已在 VS 2015 RTM 中解决。