28 Aralık 2020 Pazartesi

Generics ve Upper Bound

Giriş
C++ dilinde, Java'daki gibi template/generic tiplere "Upper Bound" verme imkanı yok.
 Belki yapmak ta gerekmiyor. Ancak illa ki benzer bir maktık kullanmak istersek önümüzde bir kaç seçene var

1. static_assert + std::is_base_of_v
Örnek
Şöyle yaparız
template<class T> class MyClass{
  static_assert(std::is_base_of_v<Draw_Shape,T>);
};
2. std::enable_if_t ile SFINAE
Açıklaması şöyle
note that the =true does not compare the test to the value true. It is not ==true. What is going on here is ridiculously complex and annoying; using SFINAE for this purpose is a hack, and this is just a monkey-see monkey-do way to make it clean.
Şöyle yaparız. Buradaki std::enable_if_t<...> = true kullanımı, normal kullanımdan biraz daha farklı. Normal kullanım için std::enable_if_t Alias'ı yazısına bakabilirsiniz.
template<class T,
  std::enable_if_t<std::is_base_of_v<Draw_Shape,T>, bool> =true
>
class MyClass{
};
3. C++20 concepts
Örnek - std::is_base_of_v
Şöyle yaparız
template<class T> requires std::is_base_of_v<Draw_Shape,T>
class MyClass{
};
Örnek - std::is_derived_from
std::is_derived_from yazısına taşıdım

Hiç yorum yok:

Yorum Gönder