What are some reasonable stylistic limits on type inference?
Posted
by
Jon Purdy
on Programmers
See other posts from Programmers
or by Jon Purdy
Published on 2011-01-07T06:35:46Z
Indexed on
2011/01/07
6:58 UTC
Read the original article
Hit count: 310
C++0x adds pretty darn comprehensive type inference support. I'm sorely tempted to use it everywhere possible to avoid undue repetition, but I'm wondering if removing explicit type information all over the place is such a good idea. Consider this rather contrived example:
Foo.h
:
#include <set>
class Foo {
private:
static std::set<Foo*> instances;
public:
Foo();
~Foo();
// What does it return? Who cares! Just forward it!
static decltype(instances.begin()) begin() {
return instances.begin();
}
static decltype(instances.end()) end() {
return instances.end();
}
};
Foo.cpp
:
#include <Foo.h>
#include <Bar.h>
// The type need only be specified in one location!
// But I do have to open the header to find out what it actually is.
decltype(Foo::instances) Foo::instances;
Foo() {
// What is the type of x?
auto x = Bar::get_something();
// What does do_something() return?
auto y = x.do_something(*this);
// Well, it's convertible to bool somehow...
if (!y) throw "a constant, old school";
instances.insert(this);
}
~Foo() {
instances.erase(this);
}
Would you say this is reasonable, or is it completely ridiculous? After all, especially if you're used to developing in a dynamic language, you don't really need to care all that much about the types of things, and can trust that the compiler will catch any egregious abuses of the type system. But for those of you that rely on editor support for method signatures, you're out of luck, so using this style in a library interface is probably really bad practice.
I find that writing things with all possible types implicit actually makes my code a lot easier for me to follow, because it removes nearly all of the usual clutter of C++. Your mileage may, of course, vary, and that's what I'm interested in hearing about. What are the specific advantages and disadvantages to radical use of type inference?
© Programmers or respective owner