Wesley Smith schrieb:
Hi,
I'm trying to figure out how to do some compile time C++ template
programming. I have something working that calculates the length of a
string, but I'm not sure how to evaluate what is actually being done
at compile time and what is being done at run time. Here's is my
code:
template <class T>
class StringLength
{
public:
static int eval(T* a)
{ return ((*a) == '\0') ? 0 :
(StringLength<T>::eval(a+1) + 1); }
};
template <class T>
inline int stringlength(T* a) { return StringLength<T>::eval(a); }
//in main somewhere
cout << stringlength<>("This is a string") << endl;
My GCC version is gcc version 4.0.1 (Apple Computer, Inc. build 5341).
I'm on OSX 10.4.8 on a PPC. Basically, I'm trying to find out what
compiler output I can look at or somehow query things at runtime to
find out what did and didn't compile down.
I suggest taking a close look at the generate assembler code, e.g. using
objdump:
objdump -D --demangle --reloc objfile.o | less
However, without taking a close look at the generated code, I am quite
sure that there isn't much that is compiled down. Your template isn't
actually a "template meta program" - it does not use recursive
instantiation of templates, but just recursive function calls:
static int eval(T* a)
{ return ((*a) == '\0') ? 0 :
(StringLength<T>::eval(a+1) + 1); }
This is always the same StringLength::eval() method that is recursively
invoked at *runtime*.
Daniel