fork download
  1. #include <iostream>
  2. #include <type_traits>
  3. using namespace std;
  4.  
  5. template<class T>
  6. struct Base {
  7. string name = "Base";
  8. void print() const {
  9. cout << name << endl;
  10. cout << static_cast<const T&>(*this).name << endl;
  11. }
  12. };
  13.  
  14. struct Derived1 : public Base<Derived1> {
  15. string name = "Derived1";
  16. };
  17.  
  18. struct Derived2 { // こいつを弾く仕組みが欲しい
  19. string name = "Derived2";
  20. };
  21.  
  22. // 関数テンプレートは部分特殊化できないためこんぱいるえらー
  23. template <class T, bool b = is_base_of<Base<T>, T>::value>
  24. ostream& operator << (ostream& os, const Base<T>& base) {
  25. static_assert(b, "T is not derived from Base<T>");
  26. }
  27.  
  28. template <class T>
  29. ostream& operator << <T, true> (ostream& os, const Base<T>& base) {
  30. base.print();
  31. return os;
  32. }
  33.  
  34. int main(){
  35. // Derived1 d1;
  36. // Derived2 d2;
  37. // f(d1);
  38. // f(d2);
  39. return 0;
  40. }
  41.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:29:65: error: non-class, non-variable partial specialization 'operator<< <T, true>' is not allowed
 ostream& operator << <T, true> (ostream& os, const Base<T>& base) {
                                                                 ^
stdout
Standard output is empty