You are not logged in.
specialization!
I'll give you a templated example with a function here:
template <typename T>
inline std::string to_string(const T& t)
{
std::istringstream ss;
ss << t;
return ss.str();
}
that's one of those standard conversion snippets that everyone uses... as long as T supports the "<<" operator, it will convert just fine...
Now, if you're using this function in other template based code, the problem comes up:
template <typename T>
void foo(const T& t)
{
std::string s = to_string(t);
... do something with s now...
}
it makes sense, if you want to do operations with a string... but what if the type T *was* a string... the to_string function just did a whole mess of needless operations (stringstream conversion)...
here comes template specialization to the rescue:
template <> inline std::string to_string<std::string>(const std::string& t)
{
return t;
}
there we go... no extra steps... because it's inlined to begin with, the compiler will remove it... (this is what's called a conversion shim). Now when the to_string function is called with an std::string argument, it does nothing.
Offline
I'm not absolutely sure I understand the way the last code snippet works, but I think you're right.
Although, I *assume* javac would notice that s.toString() just returns 'this' and would optimize accordingly by itself. However, that's just a this instance counter example, and not generally applicable.
Offline
Hmmm, it seems I didn't explain it too well:
the 3rd snippit is the same as the first, however the "typename T" has been removed and all instances of "T" have been replaced with a specific type: this is template specialization... it allows for you to have different code for each type... it's a complicated form of function overloading....
what I'm saying is that, in a java generic collection, you may have all this code that works for all types, but could be optimized for one of those types... I used string above...
for instance... let's say there's a member function to count the number of characters used if the type were converted to a string... the easiest thing to do would be to convert it to a string an get the length.... however, in the case of numbers, there's a much, much more efficient way to do it (can't recall the algorithm... but you can get the number of digits with division and maybe a log10 or something...)... this is a mundane case, but even if you did want to use that math for the int version of that generic, you couldn't...
Offline
int digits = 1 + int(log(x)/log(10));
yeah it's 1 + log10(x)... but of course there's no log10 in the c stdlib...
Offline
Ok, now I get it. I think someday I'm going to have to brush up on my C++. I'm ok reading C, but C++ extras aren't too familiar.
Dusty
Offline