【问题标题】:How to get resultant type of multiplying two different types?如何获得将两种不同类型相乘的结果类型?
【发布时间】:2019-12-19 05:20:27
【问题描述】:

如何获得将两种不同类型相乘的结果类型,即

template< typename TA, typename TB>
struct multiplier
{
    using result_type = // something here finds result of TA * TB
    result_type operator()( TA a, TB b ) const
    {
        return a * b;
    }
};

我知道在 C++ 中,将两个不同类型的数值相乘是完全有效的,这将给出编译器已知类型的值。 IE。将 double 和 int 相乘将得到 double 类型的答案。

因此,在编译时类型已知的模板类中,应该可以确定将要创建的类型。实际上,可以创建一个 lambda 来返回该值的结果,即

auto foo = [](int a, float b){ return a * b;}
auto c = foo( 13, 42.0 );

这将导致c 成为float。

请注意,我只能使用 或以下的功能。

【问题讨论】:

    标签: c++11 c++ class c++11 templates return-type


    【解决方案1】:

    您可以使用decltype 来执行此操作:

    using result_type = decltype(std::declval<TA&>() * std::declval<TB&>());
    

    【讨论】:

      【解决方案2】:

      您可以为此使用decltype 和std::declval。 decltype 将为您提供表达式的类型,std::declval 将为您“创建”该类型的对象,即使它不能/您不知道如何构造它。这给了你类似的东西

      using result_type = decltype(std::declval<TA&>() * std::declval<TB&>());
      

      请注意,我对类型使用左值引用。这样做是因为默认情况下decval 会给你一个右值引用,它可能会给你一个不同的类型。

      【讨论】:

        【解决方案3】:

        除了其他答案,如果你不需要result_type供以后使用,而只指定operator()的返回类型,还有另一种方法,不为result_type定义别名在。

        您可以提供 trailing return type 和 auto return,如下所示:

        template< typename TA, typename TB>
        struct multiplier
        {
            auto operator()(TA a, TB b) const -> decltype(a * b)
        //  ^^^^^                             ^^^^^^^^^^^^^^^^^^^
            {
                return a * b;
            }
        };
        

        (See live online)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-10
          • 2019-08-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多