Reputation: 165
I try to convert this code (c# code) to c++ code
public abstract class IGID<T>
where T : IGID<T>
how do i implement such a template condition in c++ ?
Upvotes: 1
Views: 174
Reputation: 302817
The best you could do is throw a static_assert
in an empty base class that will fire on construction. You have to delay until use because all the types have to complete before you can do any such checking.
We have our assertion object:
template <typename C>
struct Require {
Require() {
static_assert(C::value, "!");
}
};
It's empty, so adds no overhead. And then we have:
template<typename T>
struct IGID : Require<std::is_base_of<IGID<T>, T>>
{
};
Even though T
is incomplete here, we don't check anything until IGID<T>
is constructed, so we're okay.
struct A : IGID<A> { }; // okay
But:
struct B : IGID<int> { };
main.cpp:8:9: error: static_assert failed "!"
static_assert(C::value, "!");
^ ~~~~~~~~
main.cpp:13:8: note: in instantiation of member function 'Require<std::is_base_of<IGID<int>, int> >::Require' requested here
struct IGID : Require<std::is_base_of<IGID<T>, T>>
^
Upvotes: 4