by pjmlp · 8y ago · 0 comments
#include <iostream>
#include <string>
#include <type_traits>
class Display {
virtual std::string fmt() = 0;
};
template<typename T>
void f(T s)
{
static_assert(std::is_base_of<Display, T>::value, "Error: T must implement Display interface");
std::cout << s << '\n';
}
int main()
{
f(7);
}
Gives the following error with clang, <source>:12:7: error: static_assert failed "Error: T must implement Display interface"
static_assert(std::is_base_of<Display, T>::value, "Error: T must implement Display interface");
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:19:7: note: in instantiation of function template specialization 'f<int>' requested here
f(7);
^
1 error generated.
Compiler returned: 1
Of course the downside is having the library author spending extra effort to write those checks.Beyond that as well, you won't get an error if you don't use f(7), that is, if your main is empty, which would affect library authors.
use std::fmt::Display;
fn f<T: Display>(s: T) {
println!("{}", s);
}
fn main() {
f(7);
}
whereas there would be no way to get `f(7)` to compile in your C++ version since you can't make `int` inherit from `Display`. _A_ downside is that the library author has to add these sorts of checks, but for me a bigger downside is that anyone who then wants to use the library has to inherit from the library's types.