Reputation: 71
Good morning, I've already searched for a few things but can't get the answer. I'm creating a generic class, and the idea is that generic data tye (typename T) should come from an interface:
this is the interface:
template<typename T> class iDataType{
public:
virtual bool writeOnFile(std::fstream& theFile,T& data) = 0;
virtual T readOnFile(std::fstream& theFile) = 0;
};
And this is what I'm 'trying' to do:
template <typename T : public iDataType> class Database{};
thank you for your time.
Upvotes: 4
Views: 277
Reputation: 7528
The requirement that T
derive from iDataType<T>
in the limited context of the question does not seem to add value. But, to answer the question as I interpret it, the property you want to be true is:
std::is_convertible_v<T*, iDataType<T>*>
std::is_base_of
is misleading in that it will answer whether T
has a base of iDataType<T>
, but the language requires a public unambiguous base for a T&
to be used as an iDataType<T>&
. So, in C++, when you want to know if something has a base class as an interface, std::is_base_of
is wrong.
Upvotes: 3
Reputation: 13749
You can assert on compile-time condition with static_assert
, and there is std::is_base_of
.
So the solution is:
template <typename T> class Database{
static_assert(std::is_base_of<iDataType<T>, T>::value, "should be derived from iDataType");
};
Note that the solution is for C++11, for later C++ Standard you can use std::is_base_of_v
and terse static_assert
(without string literal parameter).
Upvotes: 3