Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Template trouble




On 2006 Aug 28, at 3:00 PM, Edward K. Chew wrote:

Oh, I forgot to mention, I have run into trouble with template specialization.  For example, I have a function along the lines:


template <typename T> UInt32 myHashFunction(T value, int hashBitLength);


I specialized this for C strings:


template <> UInt32 myHashFunction(const char *str, int hashBitLength);


You didn't declare the specialization correctly.  Try this way:
template<typename T>
void dostuff(T &t)
    {
    CFShow(CFSTR("Generic Do Stuff"));
    }
template<>
void dostuff<int>(int &t)
    {
    CFShow(CFSTR("Int Do Stuff"));
    }
typedef int* intptr; // because gcc chokes on directly declaring a reference to a pointer
template<>
void dostuff<int*>(intptr &t)
    {
    CFShow(CFSTR("Int* Do Stuff"));
    }
int main(int argc, char* argv[])
    {
    OSStatus error = noErr;
    char c = 'c';
    int i = 5;
    int *p = &i;
    dostuff(c);
    dostuff(i);
    dostuff(p);
    return error;
    }

It give me the following output:
Generic Do Stuff
Int Do Stuff
Int* Do Stuff

Another important note.  At least with gcc, you need to keep the const and references specifiers consistent across the specializations.
If the initial template is declared like this:
template<typename T> void dostuff(const T &t);
Then you need to declare the other ones like this:
template<> void dostuff<int>(const int &t);
template<> void dostuff<int*>(const intptr &t);

Adin Hunter Baber

"The more I learn, the more I learn how little I know."
    -- Socrates


 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/xcode-users/email@hidden

This email sent to email@hidden

References: 
 >FSRef_fopen alternative (From: "Edward K. Chew" <email@hidden>)
 >Template trouble (From: "Edward K. Chew" <email@hidden>)
 >Re: Template trouble (From: "Edward K. Chew" <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.