When using the compile-time duck typing inherent with the template style, is there any way to enforce the requirement that the template argument implements certain methods with certain signatures?
struct ProtocolT {
void g() const;
void h();
}
// I want the compiler to check that T conforms to ProtocolT
// that is, T must implement g() and h() rather than just g()
template <typename T>
void f(const T& x) {
x.g();
}
Of course, even without this, there is perfect type safety: if the template argument T
does not have a method used in the template function implementation, the compiler will always complain.
But I find it appealing to state clearly that class T
must have all the methods specified in some class ProtocolT
. It would allow me to constrain the design earlier in the development process by requiring methods from T
that I don't yet use in the template function implementation.
Even if I didn't include any unused methods in ProtocolT
, I still think a verified protocol conformance would help when I need to write a class usable as T
. (Of course, no one stops me from writing ProtocolT
for documentation purposes, but then the compiler won't validate that ProtocolT
includes at least all the required methods.)