News for hackers. Stuff that matters.
Re:Writing Complex Macros in Rust: Reverse Polish Notation by pjmlp on Thursday February 01, 2018 @01:54PM (#16284593)
Your example in C++17,

    #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.
Re:Writing Complex Macros in Rust: Reverse Polish Notation by steveklabnik on Thursday February 01, 2018 @02:08PM (#16284757)
Totally! There's a lot of code out there that doesn't do this, even if it could. That's also a lot more code, so I imagine people do it less often as well.

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.

Re:Writing Complex Macros in Rust: Reverse Polish Notation by ljrmorgan on Friday February 02, 2018 @09:09AM (#16290566)
This is not really the same though, because the Rust version compiles after the bounds have been added:

  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.