我有两个版本的代码都使用
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下向上编译,而不需要对代码进行重大更改。上面的代码本身是从大量代码中提取出来的,除了说明编译器错误之外,不一定有任何意义。