[ create a new paste ] login | about

Link: http://codepad.org/XdBKCAsh    [ raw code | output | fork ]

C++, pasted on Feb 22:
template<class Test, class Base>
struct AssertSameOrDerivedFrom {
  AssertSameOrDerivedFrom() { &constraints; }
public:
  static void constraints() {
    Test *pd = 0;
    Base *pb = pd;
  }
};

struct Base {};

template<class T>
struct YourClass {
  YourClass() {
    AssertSameOrDerivedFrom<T, Base>();
  }
};

struct Derived : Base {};
struct NotDerived {};

int main() {
  YourClass<Base>();        // No error.
  YourClass<Derived>();     // No error.
  YourClass<NotDerived>();  // Compiler error points here.
}


Output:
1
2
3
4
5
6
t.cpp: In static member function 'static void AssertSameOrDerivedFrom<Test, Base>::constraints() [with Test = NotDerived, Base = Base]':
t.cpp:4:   instantiated from 'AssertSameOrDerivedFrom<Test, Base>::AssertSameOrDerivedFrom() [with Test = NotDerived, Base = Base]'
t.cpp:17:   instantiated from 'YourClass<T>::YourClass() [with T = NotDerived]'
t.cpp:27:   instantiated from here
Line 7: error: cannot convert 'NotDerived*' to 'Base*' in initialization
compilation terminated due to -Wfatal-errors.


Create a new paste based on this one


Comments: