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

Visual Studio中的Decltype cast运算符

  •  4
  • bartop  · 技术社区  · 8 年前

    考虑以下代码示例:

    #include <algorithm>
    
    template<class T, class U>
    struct lazy_caller{
        lazy_caller(T &&one, U &&two) : m_one(one), m_two(two){} 
    
        operator decltype(std::max(T(), U()))() const {
            return std::max(m_one, m_two);
        }
    
        T m_one;
        U m_two;
    };
    
    int main()
    {
        lazy_caller<int, int> caller(1, 2);
        int i = caller;
        return 0;
    }
    

    可以想象,在实际代码中,我想做更复杂的类型推导,以创建适当的转换运算符。无论如何,这段代码并没有在VS2017中编译(我想早期版本也是如此),所以我想问一下,是否有解决这个问题的方法?我已经试过了:

    operator auto () const
    

    它还会生成编译器错误,如:

    source_file.cpp(8): error C2833: 'operator function-style cast' is not a recognized operator or type
    

    msvc有没有解决这个问题的方法? 因为gcc两者都没有问题 operator auto 也没有 operator decltype(..) .

    2 回复  |  直到 8 年前
        1
  •  3
  •   John McFarlane    7 年前

    你和 operator auto () const . 这表明 workaround 涉及使用C++11函数语法:

    operator auto() const -> decltype(std::max(T(), U())) {
        return std::max(m_one, m_two);
    }
    
        2
  •  2
  •   max66    8 年前

    msvc有没有解决这个问题的方法?

    通过一个 using 别名

    using maxType = decltype(std::max(T(), U()));
    
    operator maxType () const {
        return std::max(m_one, m_two);
    }
    

    或者,也许更好,使用 std::declval() ,

    using maxType = decltype(std::max(std::declval<T>(), std::declval<U>()));
    

    如果这不起作用,您可以尝试为 lazy_caller 班类似于

    template <typename T, typename U,
       typename R = decltype(std::max(std::declval<T>(), std::declval<U>()))>
    struct lazy_caller
     {
       lazy_caller(T && one, U && two) : m_one(one), m_two(two)
        { } 
    
       operator R () const
        { return std::max(m_one, m_two); }
    
       T m_one;
       U m_two;
     };