How to precompute array of values? - c++

Is there a way to pre-compute an array of values based on templates? In the following example I would like the 'powers_of_2' array to have 256 values computed at compile-time if that is possible without having to type all of the values.
#include <iostream>
using namespace std;
template <int X, char Y>
struct power {
enum { value = X * power<X,Y-1>::value };
};
template <int X>
struct power<X,1> {
enum { value = X };
};
template <int X>
struct power<X,0> {
enum { value = 1 };
};
int _tmain(int argc, _TCHAR* argv[])
{
int powers_of_2[] = { power<2,0>::value, power<2,1>::value, ..., power<2,255>::value };
cout << powers_of_2[1] << endl;
return 0;
}

Unless you plan on using a big integer package you will overflow the integer type at 2^32 (or 2^64, depending), but to answer your real question look at this wikipedia article on template metaprogramming.

That is exactly what a macro is useful for...

Holding the value 2^255 would require 32 bytes. This cannot be held in an int; you'd need a char array
typedef unsigned char BYTE32[32];
BYTE32 powers_of_2[256] =
{
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0},
// :
// :
{32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
};

What I do in situations like that is write a small program that generates and writes to a file the array initialization in C++ source and then #include that file. This technique is simple and effective.

You could easily write a small script to prepopulate the array for you using your preferred scripting language. Depending on the compiler and preprocessor you use, you should also be able to do it as a macro.

I agree with Lokkju. It is not possible to initialize the array by only means of template metaprogramming and macros in this case are very useful. Even Boost libraries make use of macros to implement repetitive statements.
Examples of useful macros are available here: http://awgn.antifork.org/codes++/macro_template.h

Related

Gaining access to the tuple by string template param

A standard tuple in C++ 11 allows access by the integer template param like this:
tuple<int, double> test;
test.get<1>();
but if I want get access by the string template param:
test.get<"first">()
how can I implement it?
You can create custom constexpr cast function. I just wanted to show that what the OP wants is (almost) possible.
#include <tuple>
#include <cstring>
constexpr size_t my_cast(const char * text)
{
return !std::strcmp(text, "first") ? 1 :
!std::strcmp(text, "second") ? 2 :
!std::strcmp(text, "third") ? 3 :
!std::strcmp(text, "fourth") ? 4 :
5;
}
int main()
{
std::tuple<int, double> test;
std::get<my_cast("first")>(test);
return 0;
}
This can be compiled with C++11 (C++14) in GCC 4.9.2. Doesn't compile in Visual Studio 2015.
First of all, std::tuple::get is not a member function. There is a non-member function std::get.
Given,
std::tuple<int, double> test;
You cannot get the first element by using:
std::get<"first">(test);
You can use other mnemonics:
const int First = 0;
const int Second = 1;
std::get<First>(test);
std::get<Second>(test);
if that makes the code more readable for you.
R Sahu gives a couple of good mnemonics, I wanted to add another though. You can use a C style enum (i.e. non-class enum):
enum TupleColumns { FIRST, SECOND };
std::get<FIRST>(test);
If you combine enums with a smart enum reflection library like so: https://github.com/krabicezpapundeklu/smart_enum, then you can create a set of enums that have automatic conversions to and from string. So you could automatically convert column names into enums and access your tuple that way.
All this requires you to commit to your column names and orders at compile time. In addition, you'll always need to use string literals or constexpr functions, so that you can get the enum value as constexpr to use it this way.
constexpr TupleColumns f(const char *);
constexpr auto e = f("first");
std::get<e>(test);
I should probably add a warning at this point: this is all a fairly deep rabbit hole, fairly strong C++ is required. I probably would look for a different solution in the bigger picture, but I don't know your bigger picture well enough, nor do I know the level of your C++ nor your colleagues (assuming you have them).

sizeof in variadic template c++

I need to know how many items in parameter pack of a variadic templete.
my code:
#include <iostream>
using namespace std;
template <int... Entries>
struct StaticArray
{
int size = sizeof... (Entries);// line A
//int array[size] = {Entries...};// line B
};
int main()
{
StaticArray<1,2,3,4> sa;
cout << sa.size << endl;
return 0;
}
I got compilation error on line A.
if change this line to
static const unsigned short int size = sizeof...(Arguments)
It can be compiled. my first question is why I need "static const unsigned short" to get compiled.
as you can see, I need a size to put in on my array. my final goal is able to print this array out in main function.
please help. thanks..
my ideal comes from this website but i dont know how to make it works
http://thenewcpp.wordpress.com/2011/11/23/variadic-templates-part-1-2/
As per the comments, I think this is a bug in g++'s handling of the new in-class initialisation of member variables. If you change the code to
template <int... Entries>
struct StaticArray
{
static const int size = sizeof...(Entries); // works fine
};
then it works correctly, because this uses the C++03 special case of initialising static const integral members in-class.
Similarly, if you use the new C++11 uniform initialisation syntax, it works correctly:
template <int... Entries>
struct StaticArray
{
int size{sizeof...(Entries)}; // no problem
};
I'm pretty sure the assignment form is valid here, so I think g++ (4.8.2 on my system) is getting it wrong.
(Of course, the size can't change at run-time, so the correct declaration would probably be static constexpr std::size_t size anyway, avoiding this problem...)

What is sizeof(something) == 0?

I have a template that takes a struct with different values, for example:
struct Something
{
char str[10];
int value;
...
...
};
And inside the function I use the sizeof operator: jump in memory sizeof(Something);
Sometimes I would like to not jump anything at all; I want sizeof to return zero. If I put in an empty struct it will return 1; what can I put in the template to make sizeof return zero?
sizeof will never be zero. (Reason: sizeof (T) is the distance between elements in an array of type T[], and the elements are required to have unique addresses).
Maybe you can use templates to make a sizeof replacement, that normally uses sizeof but is specialized for one particular type to give zero.
e.g.
template <typename T>
struct jumpoffset_helper
{
enum { value = sizeof (T) };
};
template <>
struct jumpoffset_helper<Empty>
{
enum { value = 0 };
};
#define jumpoffset(T) (jumpoffset_helper<T>::value)
What do you think about it?
#include <iostream>
struct ZeroMemory {
int *a[0];
};
int main() {
std::cout << sizeof(ZeroMemory);
}
Yes, output is 0.
But this code is not standard C++.
No object in C++ may have a 0 size according to the C++ standard. Only base-class subobjects MAY have 0 size but then you can never call sizeof on those. What you want to achieve is inachievable :)
or, to put it mathematically, the equation
sizeof x == 0 has no object solution in C++ :)

What is a common C/C++ macro to determine the size of a structure member?

In C/C++, how do I determine the size of the member variable to a structure without needing to define a dummy variable of that structure type? Here's an example of how to do it wrong, but shows the intent:
typedef struct myStruct {
int x[10];
int y;
} myStruct_t;
const size_t sizeof_MyStruct_x = sizeof(myStruct_t.x); // error
For reference, this should be how to find the size of 'x' if you first define a dummy variable:
myStruct_t dummyStructVar;
const size_t sizeof_MyStruct_x = sizeof(dummyStructVar.x);
However, I'm hoping to avoid having to create a dummy variable just to get the size of 'x'. I think there's a clever way to recast 0 as a myStruct_t to help find the size of member variable 'x', but it's been long enough that I've forgotten the details, and can't seem to get a good Google search on this. Do you know?
Thanks!
In C++ (which is what the tags say), your "dummy variable" code can be replaced with:
sizeof myStruct_t().x;
No myStruct_t object will be created: the compiler only works out the static type of sizeof's operand, it doesn't execute the expression.
This works in C, and in C++ is better because it also works for classes without an accessible no-args constructor:
sizeof ((myStruct_t *)0)->x
I'm using following macro:
#include <iostream>
#define DIM_FIELD(struct_type, field) (sizeof( ((struct_type*)0)->field ))
int main()
{
struct ABC
{
int a;
char b;
double c;
};
std::cout << "ABC::a=" << DIM_FIELD(ABC, a)
<< " ABC::c=" << DIM_FIELD(ABC, c) << std::endl;
return 0;
}
Trick is treating 0 as pointer to your struct. This is resolved at compile time so it safe.
You can easily do
sizeof(myStruct().x)
As sizeof parameter is never executed, you'll not really create that object.
Any of these should work:
sizeof(myStruct_t().x;);
or
myStruct_t *tempPtr = NULL;
sizeof(tempPtr->x)
or
sizeof(((myStruct_t *)NULL)->x);
Because sizeof is evaluated at compile-time, not run-time, you won't have a problem dereferencing a NULL pointer.
In C++11, this can be done with sizeof(myStruct_t::x). C++11 also adds std::declval, which can be used for this (among other things):
#include <utility>
typedef struct myStruct {
int x[10];
int y;
} myStruct_t;
const std::size_t sizeof_MyStruct_x_normal = sizeof(myStruct_t::x);
const std::size_t sizeof_MyStruct_x_declval = sizeof(std::declval<myStruct_t>().x);
From my utility macros header:
#define FIELD_SIZE(type, field) (sizeof(((type *)0)->field))
invoked like so:
FIELD_SIZE(myStruct_t, x);

Template Metaprogramming - Difference Between Using Enum Hack and Static Const

I'm wondering what the difference is between using a static const and an enum hack when using template metaprogramming techniques.
EX: (Fibonacci via TMP)
template< int n > struct TMPFib {
static const int val =
TMPFib< n-1 >::val + TMPFib< n-2 >::val;
};
template<> struct TMPFib< 1 > {
static const int val = 1;
};
template<> struct TMPFib< 0 > {
static const int val = 0;
};
vs.
template< int n > struct TMPFib {
enum {
val = TMPFib< n-1 >::val + TMPFib< n-2 >::val
};
};
template<> struct TMPFib< 1 > {
enum { val = 1 };
};
template<> struct TMPFib< 0 > {
enum { val = 0 };
};
Why use one over the other? I've read that the enum hack was used before static const was supported inside classes, but why use it now?
Enums aren't lvals, static member values are and if passed by reference the template will be instanciated:
void f(const int&);
f(TMPFib<1>::value);
If you want to do pure compile time calculations etc. this is an undesired side-effect.
The main historic difference is that enums also work for compilers where in-class-initialization of member values is not supported, this should be fixed in most compilers now.
There may also be differences in compilation speed between enum and static consts.
There are some details in the boost coding guidelines and an older thread in the boost archives regarding the subject.
For some the former one may seem less of a hack, and more natural. Also it has memory allocated for itself if you use the class, so you can for example take the address of val.
The latter is better supported by some older compilers.
On the flip side to #Georg's answer, when a structure that contains a static const variable is defined in a specialized template, it needs to be declared in source so the linker can find it and actually give it an address to be referenced by. This may unnecessarily(depending on desired effects) cause inelegant code, especially if you're trying to create a header only library. You could solve it by converting the values to functions that return the value, which could open up the templates to run-time info as well.
"enum hack" is a more constrained and close-enough to #define and that helps to initialise the enum once and it's not legal to take the address of an enum anywhere in the program and it's typically not legal to take the address of a #define, either. If you don't want to let people get a pointer or reference to one of your integral constants, an enum is a good way to enforce that constraint. To see how to implies to TMP is that during recursion, each instance will have its own copy of the enum { val = 1 } during recursion and each of those val will have proper place in it's loop. As #Kornel Kisielewicz mentioned "enum hack" also supported by older compilers those forbid the in-class specification of initial values to those static const.