我有两个版本的代码都使用decltype
和declval
。一种有效,一种无效。它们包括在下面。我已经在 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 上编译代码。上面的代码本身是从大量代码中提取的,除了演示编译器错误之外,不一定有任何意义。