Typedef

Could someone just give me a few examples of using typedef? My teacher uses it a lot, and I want to be able to start using it. Thanks much!

Ryan
All it does it create a alias of a type. The syntax is from C and is a bit awkward, so C++11 has a new form that also supports more functionality.
1
2
typedef std::string str; //str is now an alias of std::string
using s = std::string; //s is now an alias of std::string 
The latter form is preferred because it is easier to read and write - it makes more sense than the C syntax.

The latter form can also be templated, unlike the first form:
1
2
3
4
5
6
7
8
template<typename T>
using vec = std::vector<T>;

//...

vec<int> a;
vec<std::string> b;
using dvec = vec<double>;


Personally, I like to use aliases to indicate how a type should be treated. It's simpler than creating a full-blown class in most cases and can be easily swapped-out.
Last edited on
http://en.cppreference.com/w/cpp/language/typedef

However, C++11 has type alias, which is even more fun.
so say I am using an array.

It would go something like:
 
typedef std::array<float, 100> storage_type;


?
using storage_t = std::array<float, 100>;

Save your fingers. Everyone knows what blah_t is short for.
Last edited on
Topic archived. No new replies allowed.