首页 > 解决方案 > C++ 类类型转换器/类型转换的表达式

问题描述

在 Windows 10 中使用 MS Visual Studio C++ 版本 15.9.11。为什么下面代码中显示的行无法编译?我怀疑这是一个编译器错误。谢谢。

#include <type_traits>

struct C
{
    int foo();
    operator int() { return 1; };
};

// Using the C class inline
using C_foo_t = decltype( std::declval<C>().foo() );
using C_operator_int_t = decltype( std::declval<C>().operator int() );

static_assert( std::is_same< int, C_foo_t >::value, "");; // Ok
static_assert( std::is_same< int, C_operator_int_t >::value, ""); // Ok

// Through a template
template <typename T>
using foo_t = decltype( std::declval<T>().foo() );

template <typename T>
using operator_int_t = decltype( std::declval<T>().operator int() );

static_assert( std::is_same< int, foo_t<C> >::value, ""); // Ok
static_assert( std::is_same< int, operator_int_t<C> >::value, ""); // error C2057: expected constant expression

int main() { return 0; }

标签: c++

解决方案


我在 gcc 9.1 和 clang 8.0 上都尝试了 OP 的代码(对于 gcc, https: //godbolt.org/z/N5FMOe,对于 clang,使用下拉菜单,参数相同):代码编译没有问题。MSVC 19.21 ( https://godbolt.org/z/h7S_wu ) 有上述问题。

我将问题减少到最低限度,并且能够使用所有 3 个编译器成功编译(MSVC:https ://godbolt.org/z/uoifY4,clang/gcc : https ://godbolt.org/z/ D7zPY )

#include <type_traits>

struct C
{
    int foo();
    operator int() { return 1; };
};

template <typename T>
auto oper_int(const T&) -> decltype( std::declval<T>().operator int() );

template<typename T>
struct  operator_int_t{
    using type = decltype(oper_int(std::declval<T>())); 
};

static_assert( std::is_same< int, operator_int_t<C>::type >::value, ""); // works now

int main() { return 0; }

据我所知,这段代码等同于 OP(授予:这是丑陋的),但它适用于 MSVC,我倾向于认为它是一个 MSVC 错误。


推荐阅读