using nested struct slot as a type specifier?

a timespec from time.h looks like this on BSD:

1
2
3
4
5

struct timespec {
 time_t tv_sec;
 long tv_nsec;
};


I want to base a template on these types from the timespec struct
but to be portable I want to do it without explicitly naming them,
I have tried, and failed, like this:

1
2
3
4
5

template<typename T>
class nsecs {
    T.tv_nsec   value;
};


or this:
1
2
3
4
5
6
7

template <typename T>
struct nsecs {
    typename T.tv_nsec value;

};

or this:
1
2
3
4
5
6

template<typename T>
class nsecs {
    T  value;
};
nsecs<timespec.tv_nsec> p;




or is there a way to typedef it like:

typedef timespec.tv_nsec nanos;



There's nothing in the syntax of timespec that says that tv_nsec is a nanosecond, it's a semantic definition. So I don't think you can pull timespec apart to get an enforcing syntax. You may have to just resort to a plan old typedef:
typedef long nanosec_t;

In Windows, there's a high resolution timer that takes type LARGE_INTEGER, essentially a uint64_t, but is in fact a union, allowing you to get to high/low parts. I have wrapper that typedefs it, but within the class:
1
2
3
4
	class HRTimer
	{
	public:
		typedef	LARGE_INTEGER timer_t;	/// High Resolution Timer integral time type 

It defines it's own type, but clients alway use:
HRTimer::timer_t, which is quite clear in code what kind of time type it is.
Last edited on

yes, that's what I wanted to avoid.
the timespec struct has a long on BSD but might be different on
linux or Solaris. Or may change with versions of gcc.

the nearest I can get is:
1
2
timespec ts;
typedef typeof(ts.tv_nsec) nsec_type;


but the typeof doesn't seem to be standard.
not with gcc -std=c++98 anyway.

maybe I am just super-anal!
Nothing anal about it. As you can see, it's pretty much standard in STL to provide typedefs for the members so you can do exactly that. But with old C types, ...

Another alternative to still you some typedef, but put it in the platform specific section of your component; config.h or whatever you use.
phew! found a compliant solution with a bit of a boost!
just need to declare an instance of the struct first.
can't have everything.

1
2
3
4
5
6
#include <boost/typeof/typeof.hpp>

timespec ts;
typedef BOOST_TYPEOF(ts.tv_nsec) nano_type;
typedef BOOST_TYPEOF(ts.tv_sec) second_type;
Last edited on
They think of everything! Thanks for the info.
Topic archived. No new replies allowed.