代码之家  ›  专栏  ›  技术社区  ›  bradgonesurfing

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

  •  1
  • bradgonesurfing  · 技术社区  · 7 年前

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   YSC    7 年前

    为了取悦那辆小车MSVC,你可以做一部分( demo ):

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

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

    推荐文章