C++模板:重载operator +,而返回类型由输入类型决定

Yan*_*Zhu 2 c++ templates operator-overloading

假设我有以下课程

template<unsigned char B, unsigned char F>
class Foo
{
   .....
}
Run Code Online (Sandbox Code Playgroud)

我希望重载运算符+以便如果两个输入都是

Foo<B1, F1> 
Run Code Online (Sandbox Code Playgroud)

Foo<B2, F2>, 
Run Code Online (Sandbox Code Playgroud)

分别,我想返回的值是类型

Foo<max(B1, B2), max(F1, F2)>. 
Run Code Online (Sandbox Code Playgroud)

或类似的东西

Foo<max(B1-F1, B2-F2)+max(F1, F2), max(F1, F2)>. 
Run Code Online (Sandbox Code Playgroud)

有小费吗?

Joe*_*cou 5

只需在operator + return类型中计算你的新类型,并使用MPL进行比较.此外,你不需要朋友,因为你的运算符+都不需要是可变的.

简单类的简单示例:

#include <boost/mpl/max.hpp>

template<unsigned char B, unsigned char F>
class Foo
{};

template< unsigned char B1, unsigned char F1
        , unsigned char B2, unsigned char F2
        >
Foo< boost::mpl::max_<boost::mpl_::char_<B1>, boost::mpl_::char_<B2> >::value
   , boost::mpl::max_<boost::mpl_::char_<F1>, boost::mpl_::char_<F2> >::value
   >
operator+(Foo<B1,F1> const& a, Foo<B2,F2> const& b)
{
  Foo< boost::mpl::max_<boost::mpl_::char_<B1>, boost::mpl_::char_<B2> >::value
   , boost::mpl::max_<boost::mpl_::char_<F1>, boost::mpl_::char_<F2> >::value
   > that;
  return that;
}
Run Code Online (Sandbox Code Playgroud)

现在,请注意它是多么繁琐.在这种情况下,通常的习惯是尽可能使用Boost MPL积分类型而不是原始值

#include <boost/mpl/max.hpp>

template<class B, class F>
class Foo
{};

template< class B1, class F1
        , class B2, class F2
        >
Foo< typename boost::mpl::max_<B1, B2>::type
   , typename boost::mpl::max_<F1, F2>::type
   >
operator+(Foo<B1,F1> const& a, Foo<B2,F2> const& b)
{
   Foo< typename boost::mpl::max_<B1, B2>::type
      , typename boost::mpl::max_<F1, F2>::type
      > that;
  return that;
}

Foo< boost::mpl::int_<4>, boost::mpl::int_<8> > x;
Run Code Online (Sandbox Code Playgroud)

编辑:另外,这使得在pre_C++ 11 auto中写入的返回类型有点复杂.另一个经典的东西是将它变成一个遵循result_of协议的函数对象,这样你就可以使用元函数以不透明的方式计算返回类型.