I have a class that takes in its constructor a std::function<void(T)>
. If I declare T to be a double, but pass the constructor a lambda that takes an int, the compiler let's me get away without a warning. (Update: MSVC issues a warning, clang does not). Is it possible to modify this code so that I get a compiler error (w/ clang)?
I was surprised this works:
#include <functional>
#include <iostream>
template <typename T>
class Thing {
public:
using Handler = std::function<void(T)>;
Thing(Handler handler)
: handler_(handler)
{}
Handler handler_;
};
int main() {
Thing<double> foo([](int bar) { // Conversion to void(int) from void(double)
std::cout << bar;
});
foo.handler_(4.2);
return 0;
}
...and compiles without a warning:
$ clang --std=c++11 -lc++ -Wall -Werror test.cc
$ ./a.out
4
It seems like such a conversion could result in unwanted side effects. I can't imagine a case where this would ever be desired behavior.