c++ - 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; }
解决方案
我在 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 错误。
推荐阅读
- python - OpenCV 中的光流大小
- python - 我正在研究一个不和谐的机器人,我需要一个货币系统。不幸的是,每次我运行代码时,它都会给我一个关键错误
- mysql - HATEOAS RepresentationModelAssembler,带有 JSON 正文的 POST 返回 500:IllegalArgumentException:没有足够的变量值可用于扩展“id”
- sql - DELPHI:需要从列表框项中获取字段的值?
- webrtc - 如何使用 JsSIP 通知远程方视频/音频静音/取消静音
- c# - 使组件上的脚本仅适用于一个游戏对象?统一
- ajax - Hangfire 仪表板更改刷新周期
- symfony - SonataBlock - 添加输入 ModelListType
- google-calendar-api - 如何在 integromat 中格式化来自谷歌日历和 Dialogflow 的“开始日期”?
- javascript - 如何在javascript中选择和切换div内的元素