在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS

How to use decltype as the LHS of a larger type expression when compiling under VS2010-VS2015

本文关键字:类型 表达式 LHS decltype 编译 VS2010-VS2015 何使用      更新时间:2023-10-16

我有两个版本的代码,都使用decltypedeclval。一个有效,一个无效。它们包括在下面。我在VS2017及以下版本上测试过,得到了相同的结果。VS2018将对其进行编译。GCC和Clang都对其进行了编译。

MSVC下为失败情况生成的错误为

[x86-64 MSVC 19 2017 RTW#1]错误C3646:"类型":未知覆盖说明符

对于行

typedef typename decltype(boost::declval<Func>()(SegmentVec()))::value_type type;

有关以下代码的实时版本,请参阅God Bolt。

#include <vector>
#include "boost/type_traits/declval.hpp"
typedef std::vector<int> SegmentVec;
/////////////////////////////////
// The below fails
template <typename Func> struct Traits {
typedef typename decltype(boost::declval<Func>()(SegmentVec()))::value_type type;
};
template <typename F> auto Hof(F f) -> typename Traits<F>::type {
return f(std::vector<int>{2})[0];
}
/////////////////////////////////

/////////////////////////////////
// The below works
template <typename Func> struct Traits2 {
typedef typename decltype(boost::declval<Func>()(SegmentVec())) type;
};
template <typename F> auto Hof2(F f) -> typename Traits2<F>::type {
return f(std::vector<int>{2});
}
/////////////////////////////////

int main(){
auto lmd = [](std::vector<int> const & a){return a;}; 
Hof(lmd);
Hof2(lmd);
}

是否可以在不显著更改代码的情况下,在MSVC 2010下向上编译代码。上面的代码本身是从更大的代码体中提取的,除了演示编译器错误之外,不一定有任何意义。

为了取悦那个有缺陷的MSVC,你可以在部分(演示(中完成:

template <typename Func> struct Traits {
typedef decltype(boost::declval<Func>()(SegmentVec())) suptype;
typedef typename suptype::value_type type;
};

using Tnew = Told;是更好的语法;(

相关文章: