четверг, 24 января 2013 г.

Подъем настроения от учеников pattern matching в C++

Сотрудница (ну и ученица тоже, я ее взял с нулевым опытом) порадовала во время код ревью, сопоставление с образцом в C++, код упрощенный естественно.



struct BaseClass
{
    ;
};
struct Derived1:BaseClass
{
    ;
};
struct Derived2:BaseClass
{
    ;
};
struct MostDerived:Derived1, Derived2
{
    ;
};



template
constexpr (нахрена???) void patternMatchingFunction(const Type& el)
{
    try
    {
        throw el;
    }
    catch (const int& i)
    {
        std::cout << "this is int" << std::endl;
    }
    catch(const float& f)
    {
        std::cout << "this is float" << std::endl;
    }
    catch(const Derived1& d)
    {
        std::cout << "this is Derived1" << std::endl;
    }
    catch(const Derived2& d)
    {
        std::cout << "this is Derived2" << std::endl;
    }
    catch(const BaseClass& d)
    {
        std::cout << "this is BaseClass" << std::endl;
    }

    catch(const double &d )
    {
        std::cout << "this is double" << std::endl;
    }
    catch (const std::string& string)
    {
        std::cout << "this is string";
    }
    catch(...)
    {
        throw std::runtime_error("error");
    }
}

int main()
{

  patternMatchingFunction(0.2);
  patternMatchingFunction(1);
  patternMatchingFunction(0.2f);
  patternMatchingFunction(BaseClass());
  patternMatchingFunction(Derived1());
  patternMatchingFunction(Derived2());
  patternMatchingFunction(MostDerived());
  patternMatchingFunction("string");


  return 0;
}
Косяков я вижу очевидных 2
0. Непонятно нафига это надо, в ее случае просто надо было иметь несколько (специализированных) перегруженных функций
1. В случае разлапистой иерархии классов, поведение зависит от расположения матчеров, что не есть гуд.
Но полет фантазии не может не радовать.