I have:
const unsigned int hash_1 = 0xaf019b0c;
const unsigned int hash_2 = 0xf864e55c;
const unsigned int hash_3 = 0xfaea8ed5;
Hashes come from an automatically generated header. These hashes are indirectly associated with tags 1, 2, 3. The tags are associated with classes through a simple compile-time generated id. That way I can GetTag<Class1>() and get my int-tag for Class1.
My goal is to simplify the hash->tag association. Preferably this should be compile-time generated and O(1) access time. Memory in this case is not an issue. I can not use any third-party software.
I have tried the following:
template<uint32 t> size_t GetTagByHash() { return 0; }
with specific implementations like:
template<> size_t GetTagByHash<hash_1>() { return GetTag<Class1>(); }
but that kind of implementation is difficult to use since if I have a local variable uint32 my_hash; that the compiler can't determine what value it has in compile-time then the compiler is unable to resolve the correct implementation of GetTagByHash() to call.
As I understand it, your problem is how to do this lookup with run-time values as well as compile-time ones.
You've really got two questions. First, what algorithm do you want to use to do the lookup, and second, how do you tell C++ to implement that?
The algorithm to use is somewhat of a non-obvious question; you've got a list of effectively-random numbers, and you want to look up something in that list and return an associated tag. Probably you want some sort of hashtable, but to start with, I'll show some examples with something simpler -- and likely better for small numbers of hashes: A simple O(N) lookup, in pseudocode:
if i = N return tag_N
else if i = N-1 ...
...
else if i = 1 return tag_1
else return tag_0
Now, how do you tell C++ to do this? You've got to create a list of all your hash tags, and instructions for doing that. Here's a simple way:
template<int i> struct lookup
{
int result(int j) { return 0; }
};
const unsigned int hash_1 = 0xaf019b0c;
template<> struct lookup<1>
{
int result(int j)
{
if (j == hash_1)
return GetTag<Class1>();
return lookup<0>::result(j);
}
};
const unsigned int hash_2 = 0xf864e55c;
template<> struct lookup<2>
{
int result(int j)
{
if (j == hash_2)
return GetTag<Class2>();
return lookup<1>::result(j);
}
};
And so forth. Then, at the end, you can have
int hash_lookup(int j)
{
return lookup<last_hash_number>::result(j);
}
Writing out all those identical definitions is a pain, though, so it's best to let C++ do that -- and, to do that, you need to define the hashes in such a way that they can be iterated over. Let's do that:
template<int> struct hash_tag {
static const int value = 0;
typedef type void;
};
#define SET_HASH(I, VALUE, CLASS) \
template<> struct hash_tag<(I)> \
{ \
static const int value = (VALUE); \
typedef type (CLASS); \
}
SET_HASH(1, 0xaf019b0c, Class1);
SET_HASH(2, 0xf864e55c, Class2);
SET_HASH(3, 0xfaea8ed5, Class3);
// Define a general recursive lookup struct.
template<int i> struct lookup
{
int result(int j)
{
if (j == hash_tag<i>::value)
return GetTag<hash_tag<i>::type>;
return lookup<i-1>::result(j);
}
};
// Make sure the recursion terminates.
template<> struct lookup<0>
{
int result(int) { return 0; }
};
Then, you use this as before.
Now, let's return to that first question -- what algorithm do you actually want to use to do the lookup? The advantage of this iterative O(N) lookup is that it's easy to program, and it doesn't require any initialization of any data structures at run-time -- you can just call it. However, as noted, it's O(N). An alternate choice is to use a std::map object; you can use a similar recursive definition to initialize it at runtime, and then use it. That might look something like this:
// Make a typedef to save some typing.
typedef std::map<unsigned int, size_t> Map_type;
typedef std::pair<unsigned int, size_t> Map_value;
// Define a recursion to add hashes to the map.
template<int i> struct add_hash
{
void add(Map_type& hashmap)
{
hashmap.insert(
Map_value(hash_tag<i>::value,
GetTag<hash_tag<i>::type>));
add_hash<i-1>::add(hashmap);
}
};
// Make sure the recursion terminates.
template<> struct lookup<0>
{
void add(Map_type&) {}
};
// Now, create a class to initialize the std::map and do lookup.
class Hash_lookup
{
Hash_lookup() { add_hash<last_hash_number>(map_); }
int result(unsigned int j) { return map_[j]; }
private:
Map_type map_;
}
Personally, I would probably combine this with your GetTagByHash<> idea, and give the Hash_loop a "runtime-computed result" function as I described, as well as a "compile-time-computed result" function that takes a template argument rather than a function argument. But, in general, that's the basic idea for doing runtime lookup -- you put the values you want to look up into a set of templated classes that you can recursively iterate over at compile time, and then you use that recursive iteration to either define a lookup function or initialize a runtime structure that you can use for doing the lookup.
Related
I try to explain that.
I need a function which gets different numbers of parameters (2,3 or even more) and based on it returns corresponding object of struct:
someStruct funcReturn(bool par1, bool par2, ...)
{
someStruct temp;
if (par1)
{
//...
}
if (par2)
{
//...
}
...
return temp;
}
Structs is very simple:
struct ReturnTwo
{
int one;
int two;
};
struct ReturnThree
{
int one;
int two;
int three;
};
And in the end I need to assign the result of this function to a general structure consisting of four objects (missing elements are initialized 0):
struct ReturnFour
{
int one;
int two;
int three;
int four;
};
...
ReturnFour returnFour = funcReturn(true, false, ...)
My question can be divided into two parts:
Is there a way to work with different numbers of parameters in function and specify a logic of it into the function? Using templates provides that?
How can I assign one struct to another without changing the organization of struct? Something like a auto for struct? Of course I can solve that through С-style:
ReturnFour returnFour = {funcReturn(true, false).one,funcReturn(true, false).two,0 ,0}
But I think there is a more convenient way. Thank you!
Would overloaded functions work for you?
ReturnOne funcReturn(bool par1) { ... }
ReturnTwo funcReturn(bool par1, bool par2) { ... }
Etc? Another possibility is to return a struct of optionals, or a bunch of ints and flags to represent which are present.
If you intend for the runtime value of the parameters (rather than the number of them) to determine what type your function returns, then that's not possible. In that case the best you can do is one of the dynamic suggestions I gave above, since it must return just one type and you presumably want that type to indicate which values it contains.
A final idea is if your boolean values are known at compile time, you could use template parameters instead of function arguments, and then have different specializations so the combination of true/false values could select a proper specialization.
Just return a ReturnFour always. Returning different types - even if they're subsets of ReturnFour, means you have to write conversion operators or converting constructors, and that's extra work with no benefit visible in this context.
That leaves your overloads looking like
ReturnFour funcReturn(bool p1) { return {42}; }
ReturnFour funcReturn(bool p1, bool p2) { return {42, 53}; }
and the un-used members of the return struct will be value-initialized to zero.
The following solution uses templates, C++17 structured bindings and a std::tuple return type to allow for any number of arguments. As an example all the bool values that were converted to int values are added together.
#include <tuple>
int translate(bool par) // logic to translate a bool to an int
{
if (par) {
return 5;
}
else {
return -3;
}
}
template <typename T>
struct ToInt {
using Type = int;
};
template <typename... Targs>
std::tuple<typename ToInt<Targs>::Type...> funcReturn(Targs... Fargs)
{
return { translate(Fargs)... };
}
int main() {
auto [par1, par2, par3, par4] = funcReturn(true, false, true, true);
int total = par1 + par2 + par3 + par4; // total == 12
}
demo
Let have a type T and a struct having ONLY uniform elements of T type.
struct Foo {
T one,
T two,
T three
};
I'd like to access them in fallowing way:
struct Foo {
T one,
T two,
T three
T &operator [] (int i)
{
return *(T*)((size_t)this + i * cpp_offsetof(Foo, two));
}
};
where cpp_offsetof macro (it is considered to be correct) is:
#define cpp_offsetof(s, m) (((size_t)&reinterpret_cast<const volatile char&>((((s*)(char*)8)->m))) - 8)
The C++ standard doesn't guarantee it, but can we assume that members are distanced by a fixed offset and above is correct, cross-platform solution?
100% compatible solution would be:
struct Foo {
T one,
T two,
T three
T &operator [] (int i) {
const size_t offsets[] = { cpp_offsetof(Foo, one), cpp_offsetof(Foo, two), cpp_offsetof(Foo, three) };
return *(T*)((size_t)this + offsets[i]);
}
};
[edit]standard, compliant and faster version was presented by snk_kid using pointers to data members[/edit]
but it requires extra lookup table which I'm trying to avoid.
//EDIT
And one more. I cannot use just an array and constants to index these fields, they have to be named fields of a struct (some macro requires that).
//EDIT2
Why those have to be named fields of a struct? What is the macro? It is settings system of a bigger project. Simplifying it's sth like this:
struct Foo {
int one;
int two;
}
foo;
struct Setting { void *obj, size_t filed_offset, const char *name, FieldType type }
#define SETTING(CLASS, OBJ, FIELD, TYPE) { OBJ, cpp_offsetof(CLASS, FIELD), #OBJ #FIELD, TYPE }
Setting settings[] = {
SETTING(Foo, foo, one, INT_FIELD),
SETTING(Foo, foo, two, INT_FIELD)
};
And once again: I'm not looking form 100% compatible solution but 99%. I'm asking if we can expect that some compilers will put non-uniform padding between uniform fields.
Your code doesn't work with NON-POD types such those which using virtual member functions. There is a standard compliant (and efficient) way to achieve what you're trying to do, using pointer to data members:
template< typename T >
struct Foo {
typedef size_t size_type;
private:
typedef T Foo<T>::* const vec[3];
static const vec v;
public:
T one;
T two;
T three;
const T& operator[](size_type i) const {
return this->*v[i];
}
T& operator[](size_type i) {
return this->*v[i];
}
};
template< typename T >
const typename Foo<T>::vec Foo<T>::v = { &Foo<T>::one, &Foo<T>::two, &Foo<T>::three };
Just make sure you use const every with the table of pointer to data-members to get optimizations. Check here to see what I'm talking about.
Another way is with template specialization if what you are trying to achieve is still a compile time feature.
class Foo {
T one;
T two;
T three;
};
template <int i> T & get(Foo& foo);
template T& get<1>(Foo& foo){ return foo.one;}
template T& get<2>(Foo& foo){ return foo.two;}
template T& get<3>(Foo& foo){ return foo.three;}
It would be nice to define get as a member function but you cannot
specialize template member functions. Now if this is only a compile time
expansion you are looking for then this will avoid the lookup table
issue of one of the previous posts. If you need runtime resolution
then you need a lookup table obviously.
--
Brad Phelan
http://xtargets.heroku.com
You might be able to achieve what you want using an array to hold the data (so you can get indexed access without using a lookup table) and having references to the various array elements (so you can have 'named' elements for use by your macros).
I'm not sure what your macros require, so I'm not 100% sure this will work, but it might. Also, I'm not sure that the slight overhead of the lookup table approach is worth jumping through too many hoops to avoid. On the other hand, I don't think the approach I suggest here is any more complex than the table-of-pointers approach, so here it is for your consideration:
#include <stdio.h>
template< typename T >
struct Foo {
private:
T data_[3];
public:
T& one;
T& two;
T& three;
const T& operator[](size_t i) const {
return data_[i];
}
T& operator[](size_t i) {
return data_[i];
}
Foo() :
one( data_[0]),
two( data_[1]),
three( data_[2])
{};
};
int main()
{
Foo<int> foo;
foo[0] = 11;
foo[1] = 22;
foo[2] = 33;
printf( "%d, %d, %d\n", foo.one, foo.two, foo.three);
Foo<int> const cfoo( foo);
printf( "%d, %d, %d\n", cfoo[0], cfoo[1], cfoo[2]);
return 0;
}
You can't because the compiler can add dead bytes between members to allow padding.
There is two ways to do what you want.
The first is to use your compiler-specific keyword or pragma macro that will force the compiler to not add padding bytes. But that is not portable.
That said it might be the easiest way to do it with your macro requirements, so I suggest you explore this possibility and prepare for adding more pragma when using different compilers.
The other way is to first make sure your members are aligned, then add accessors :
struct Foo {
T members[ 3 ]; // arrays are guarrantied to be contigu
T& one() { return members[0]; }
const T& one() const { return members[0]; }
//etc...
};
If you're sure the compilers you're using are going to generate the right code for this (and I'd imagine they would, assuming T isn't a reference type anyway) the best thing to do is put in some kind of check that the struct is laid out as you think. I can't think of any particular reason to insert non-uniform padding between adjacent members of the same type, but if you check the struct layout by hand then you'll at least know if it happens.
If the struct (S) has exactly N members of type T, for example, you can check at compile time that they are tightly packed simply using sizeof:
struct S {
T a,b,c;
};
extern const char check_S_size[sizeof(S)==3*sizeof(T)?1:-1];
If this compiles, then they're tightly packed, as there's no space for anything else.
If you just happen to have N members, that you want to ensure are placed directly one after the other, you can do something similar using offsetof:
class S {
char x;
T a,b,c;
};
extern const char check_b_offset[offsetof(S,b)==offsetof(S,a)+sizeof(T)?1:-1];
extern const char check_c_offset[offsetof(S,c)==offsetof(S,b)+sizeof(T)?1:-1];
Depending on the compiler, this might have to become a runtime check, possibly not using offsetof -- which you might want to do for non-POD types anyway, because offsetof isn't defined for them.
S tmp;
assert(&tmp.b==&tmp.a+1);
assert(&tmp.c==&tmp.b+1);
This doesn't say anything about what to do if the asserts start failing, but you should at least get some warning that the assumptions aren't true...
(By the way, insert appropriate casts to char references and so on where appropriate. I left them out for brevity.)
I want to use an unordered_set having as key an unsigned long long*, but I want to implement the hash and the equal_to using the values stored. For instance:
int size = 4;
typedef unsigned long long verylong;
verylong* x = new verylong[size];
// calc hash and equal using x[0]..x[3]
The easy method is to use a wrapper.
class VeryLong {
verylong* array;
int arraySize;
...
bool operator==(const VeryLong& x) { // use the array and arraySize }
...
};
namespace std {
template <>
class hash<VeryLong>
{
std::size_t operator()(const VeryLong& v) const
{
// Compute hash values for array (using murmur, maybe)
//...
}
};
But I don't want to use a wrapper due to memory consumption. I want something like:
std::unordered_set<verylong*,MyHash,MyEqual> set;
The problem is to implement MyHash and MyEqual, because the arraySize is not constant (I only know arraySize in execution time).
I tried this:
typedef struct MyHash
{
int arraySize;
MyHash(int size) : arraySize(arraySize) {}
long operator() (const verylong* const k) const { return hash(k,size); }
} MyHash;
But I cannot use this, because MyHash is not constexpr.
Is what I want possible to do?
EDIT: If I try using the MyHash implemented above:
int size;
// someone sets size a positive value
std::unordered_set<verylong*,MyHash(size),MyEqual> set;
The following error occurs:
error: temporary of non-literal type 'MyHash' in a constant expression std::unordered_set< verylong*, MyHash(size), MyEquals> set;
The second template argument to std::unordered_set<> should be MyHash rather than MyHash(size), as a type is expected here rather than an object. Change your set declaration to:
std::unordered_set<verylong*, MyHash, MyEqual> set(bucket_count, MyHash(size));
Presumably MyEqual will need a similar argument for size, in which case do:
std::unordered_set<verylong*, MyHash, MyEqual> set(bucket_count, MyHash(size), MyEqual(size));
For bucket_count, use a guesstimate of how many elements will be in your set.
As a side note, don't typedef your structs that way – that's a hideous C-ism that serves no purpose in C++.
I have this problem (histogramming). I've a real space: [a,b] partitioned in some way ([a0=a, a1, a2, ..., b]). The partitioning may be with equal space (a1 - a0 = a2 - a1 = ...) or variables.
I need a class that handle this, with some methods to say given a value in which bin of the partition it belongs; other methods to find the center of a particular bin and more.
During the program I don't like to instantiate a class only to call these simple function like
Binner binner(binning);
binner.get_bin(1.3);
binner.get_centerbin(2);
so I tried to write a static class using template to do something like that:
Binner<binning>::get_bin(1.3);
Binner<binning>::get_centerbin(2);
is it a good idea? There are other way to do it? Now I've free functions like
double get_bin(double bin, Binning binning); // a lot of if/else inside
but I think it's too error prone.
Here my implementation:
enum Binning {CELL, LARGE, BE};
const double binning_LARGE[] = {0, 1.2, 1.425, 1.550, 1.800, 2.5};
const double binning_BE[] = {0, 1.425, 1.550, 2.5};
template<Binning binning>
class Binner
{
public:
static const double* bins;
static const int n;
static int get_bin(double value);
};
template<> const double* myclass<LARGE>::bins = binning_LARGE;
template<> const double* myclass<BE>::bins = binning_BE;
template<> const int myclass<LARGE>::n = sizeof(binning_LARGE) / sizeof(double);
template<> const int myclass<BE>::n = sizeof(binning_BE) / sizeof(double);
template<Binning binning> int myclass<binning>::get_bin(double value)
{
return find_if(bins, bins + n,
bind2nd(greater<double>(), value)) - bins - 1;
}
template<> int myclass<CELL>::get_bin(double value)
{
return static_cast<int>(value / 0.025);
}
is it a good implementation / design?
Is there a way to avoid the n field using std::vector? How?
Is there a way to parametrize the 0.025? I know that double can't be template parameter but can I write something similar to this:
Binner<0.025> binner;
other / advices?
Edit:
For the third point Why I can't do that:
template<Binning binning, int N=100>
class Binner
{
public:
static const double* bins;
static const int n;
static int bin(double value);
};
...
template<Binning binning, int N> int Binner<CELL, N>::bin(double value)
{
return static_cast<int>(value / (2.5 / N));
}
IMHO, your design is ok, if you do not want to instantiate a class. Indeed, it seems a kind of template metaprogramming to me. Whether this makes sense depends on how you are planning to reuse this template.
Using a std::vector would allow you to get rid of the variable to hold the array size, for sure. Now, if this is good for your design, I don't know... it would move some complexity out of your template definition, to the binning definition (which now you can initialize very simply)...
Finally, you can instantiate your template passing a constant to it:
template < Binning binning, unsigned long N, unsigned long M>
class ... {
<using N>
}
have you considered a traits class? Typically if you have static information that you want to separate from the behaviour in a class, you might consider creating a traits class that encapsulates that.
So I'd start with the default behaviour:
enum Binning {CELL, LARGE, BE};
template <Binning binning>
struct BinTraits
{
// default behaviour
int get_bin(double value) { return value / 0.025; }
};
Then I'd provide the specialisations:
const double binning_LARGE[] = {0, 1.2, 1.425, 1.550, 1.800, 2.5};
const double binning_BE[] = {0, 1.425, 1.550, 2.5};
template <typename RandomAccessCollectionT>
int get_bin_impl(double value, RandomAccessCollectionT collection, unsigned size)
{
return find_if(collection, collection + size,
bind2nd(greater<double>(), value)) - collection - 1;
}
template <>
struct BinTraits<LARGE>
{
int get_bin(double value) { return get_bin_impl(value, binning_LARGE, sizeof(binning_LARGE) / sizeof(binning_LARGE[0])); }
};
template <>
struct BinTraits<BE>
{
int get_bin(double value) { return get_bin_impl(value, binning_BE, sizeof(binning_BE) / sizeof(binning_BE[0])); }
};
Then I'd put the actual container behaviour in another class that requires binning behaviour (lets call it HashTable):
template <typename BinTraits>
class HashTable
{
public:
void insert(double value)
{
int bin = BinTraits::get_bin(value);
_bins[bin].insert(value);
}
// _bin is a multimap or something
};
Looking at the usage of find_if and bind2nd as well as functors, it seems as if you are quite knowledgeable about STL and some advanced C++ concepts; yet, what you are trying to do seems to be over-engineering. While I can't fully understand what you are trying to do but it seems that you could do away with templates completely and use just a class (instantiated with different values) and method parameters.
Let have a type T and a struct having ONLY uniform elements of T type.
struct Foo {
T one,
T two,
T three
};
I'd like to access them in fallowing way:
struct Foo {
T one,
T two,
T three
T &operator [] (int i)
{
return *(T*)((size_t)this + i * cpp_offsetof(Foo, two));
}
};
where cpp_offsetof macro (it is considered to be correct) is:
#define cpp_offsetof(s, m) (((size_t)&reinterpret_cast<const volatile char&>((((s*)(char*)8)->m))) - 8)
The C++ standard doesn't guarantee it, but can we assume that members are distanced by a fixed offset and above is correct, cross-platform solution?
100% compatible solution would be:
struct Foo {
T one,
T two,
T three
T &operator [] (int i) {
const size_t offsets[] = { cpp_offsetof(Foo, one), cpp_offsetof(Foo, two), cpp_offsetof(Foo, three) };
return *(T*)((size_t)this + offsets[i]);
}
};
[edit]standard, compliant and faster version was presented by snk_kid using pointers to data members[/edit]
but it requires extra lookup table which I'm trying to avoid.
//EDIT
And one more. I cannot use just an array and constants to index these fields, they have to be named fields of a struct (some macro requires that).
//EDIT2
Why those have to be named fields of a struct? What is the macro? It is settings system of a bigger project. Simplifying it's sth like this:
struct Foo {
int one;
int two;
}
foo;
struct Setting { void *obj, size_t filed_offset, const char *name, FieldType type }
#define SETTING(CLASS, OBJ, FIELD, TYPE) { OBJ, cpp_offsetof(CLASS, FIELD), #OBJ #FIELD, TYPE }
Setting settings[] = {
SETTING(Foo, foo, one, INT_FIELD),
SETTING(Foo, foo, two, INT_FIELD)
};
And once again: I'm not looking form 100% compatible solution but 99%. I'm asking if we can expect that some compilers will put non-uniform padding between uniform fields.
Your code doesn't work with NON-POD types such those which using virtual member functions. There is a standard compliant (and efficient) way to achieve what you're trying to do, using pointer to data members:
template< typename T >
struct Foo {
typedef size_t size_type;
private:
typedef T Foo<T>::* const vec[3];
static const vec v;
public:
T one;
T two;
T three;
const T& operator[](size_type i) const {
return this->*v[i];
}
T& operator[](size_type i) {
return this->*v[i];
}
};
template< typename T >
const typename Foo<T>::vec Foo<T>::v = { &Foo<T>::one, &Foo<T>::two, &Foo<T>::three };
Just make sure you use const every with the table of pointer to data-members to get optimizations. Check here to see what I'm talking about.
Another way is with template specialization if what you are trying to achieve is still a compile time feature.
class Foo {
T one;
T two;
T three;
};
template <int i> T & get(Foo& foo);
template T& get<1>(Foo& foo){ return foo.one;}
template T& get<2>(Foo& foo){ return foo.two;}
template T& get<3>(Foo& foo){ return foo.three;}
It would be nice to define get as a member function but you cannot
specialize template member functions. Now if this is only a compile time
expansion you are looking for then this will avoid the lookup table
issue of one of the previous posts. If you need runtime resolution
then you need a lookup table obviously.
--
Brad Phelan
http://xtargets.heroku.com
You might be able to achieve what you want using an array to hold the data (so you can get indexed access without using a lookup table) and having references to the various array elements (so you can have 'named' elements for use by your macros).
I'm not sure what your macros require, so I'm not 100% sure this will work, but it might. Also, I'm not sure that the slight overhead of the lookup table approach is worth jumping through too many hoops to avoid. On the other hand, I don't think the approach I suggest here is any more complex than the table-of-pointers approach, so here it is for your consideration:
#include <stdio.h>
template< typename T >
struct Foo {
private:
T data_[3];
public:
T& one;
T& two;
T& three;
const T& operator[](size_t i) const {
return data_[i];
}
T& operator[](size_t i) {
return data_[i];
}
Foo() :
one( data_[0]),
two( data_[1]),
three( data_[2])
{};
};
int main()
{
Foo<int> foo;
foo[0] = 11;
foo[1] = 22;
foo[2] = 33;
printf( "%d, %d, %d\n", foo.one, foo.two, foo.three);
Foo<int> const cfoo( foo);
printf( "%d, %d, %d\n", cfoo[0], cfoo[1], cfoo[2]);
return 0;
}
You can't because the compiler can add dead bytes between members to allow padding.
There is two ways to do what you want.
The first is to use your compiler-specific keyword or pragma macro that will force the compiler to not add padding bytes. But that is not portable.
That said it might be the easiest way to do it with your macro requirements, so I suggest you explore this possibility and prepare for adding more pragma when using different compilers.
The other way is to first make sure your members are aligned, then add accessors :
struct Foo {
T members[ 3 ]; // arrays are guarrantied to be contigu
T& one() { return members[0]; }
const T& one() const { return members[0]; }
//etc...
};
If you're sure the compilers you're using are going to generate the right code for this (and I'd imagine they would, assuming T isn't a reference type anyway) the best thing to do is put in some kind of check that the struct is laid out as you think. I can't think of any particular reason to insert non-uniform padding between adjacent members of the same type, but if you check the struct layout by hand then you'll at least know if it happens.
If the struct (S) has exactly N members of type T, for example, you can check at compile time that they are tightly packed simply using sizeof:
struct S {
T a,b,c;
};
extern const char check_S_size[sizeof(S)==3*sizeof(T)?1:-1];
If this compiles, then they're tightly packed, as there's no space for anything else.
If you just happen to have N members, that you want to ensure are placed directly one after the other, you can do something similar using offsetof:
class S {
char x;
T a,b,c;
};
extern const char check_b_offset[offsetof(S,b)==offsetof(S,a)+sizeof(T)?1:-1];
extern const char check_c_offset[offsetof(S,c)==offsetof(S,b)+sizeof(T)?1:-1];
Depending on the compiler, this might have to become a runtime check, possibly not using offsetof -- which you might want to do for non-POD types anyway, because offsetof isn't defined for them.
S tmp;
assert(&tmp.b==&tmp.a+1);
assert(&tmp.c==&tmp.b+1);
This doesn't say anything about what to do if the asserts start failing, but you should at least get some warning that the assumptions aren't true...
(By the way, insert appropriate casts to char references and so on where appropriate. I left them out for brevity.)