template< class type >
class SORTABLE
{
public:
bool operator<( const type& other ) const // 1
{
return ( (type&)*this ).key() < other.key();
}
template< uu mode >
static bool compare( const type& a, const type& b ) // 2
{
return a.key< mode >() < b.key< mode >();
}
};
class SOME_CLASS : public SORTABLE< SOME_CLASS >
{
...
public:
...
auto key() const // 1
{
return x * y;
}
template< uu mode >
const auto key() const // 2
{
switch( mode )
{
case 0:
return x * y;
case 1:
return x & y;
}
}
...
};
std::vector< SOME_CLASS > some_list{ { ... }, { ... }, ... };
sort( some_list.begin(), some_list.end() ); // 1
sort( some_list.begin(), some_list.end(), SOME_CLASS::compare< 1 > ); // 2
첫댓글 템플릿에 타입으로 상수를 넘겨서 그것을 스위치의 패턴 매칭에도 쓸 수 있네욤
그러네요. 아마 컴파일 타임에 코드가 결정된다고 본 것 같아요. 표준이 정해지면 좋을텐데요.
상수 조건이라 사용예에 따라 개개의 함수가 생성되는거죠. 최적화에 좋은구조. 람다로 넘기는게 편하긴 하지만, 사용처가 아닌 클래스가 룰을 가지고 있어야하는 경우도 있는지라~