By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
 449,002 Members | 1,275 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,002 IT Pros & Developers. It's quick & easy.

# Specializing on a templated type

 P: n/a Hello, Is there any way of specializing a templated function on a type which is itself templated? Here's the simplest example of the problem I can think of. Say I have written an implementation of the identity function as follows, template T identity(T x) { return x; } and for some reason I want to specialize this function for the following templated type, so that instead of returning the entire structure, the identity function only returns the single value within the structure. template struct Foo { T foo; }; Is there any way I can do something like the following? template <> template // Parameter for Foo; not legal C++ code. Foo identity(T x) { return x.foo; } Any help would be appreciated. Thanks, Alex Sep 3 '05 #1
Share this Question
2 Replies

 P: n/a Alex Drummond wrote: Is there any way of specializing a templated function on a type which is itself templated? Here's the simplest example of the problem I can think of. Say I have written an implementation of the identity function as follows, template T identity(T x) { return x; } and for some reason I want to specialize this function for the following templated type, so that instead of returning the entire structure, the identity function only returns the single value within the structure. template struct Foo { T foo; }; Is there any way I can do something like the following? template <> template // Parameter for Foo; not legal C++ code. Foo identity(T x) { return x.foo; } Any help would be appreciated. Just define an overloaded function: -------------------------------------------------------------------- template T identity(T x) { return x; } template struct Foo { T foo; }; // the following is NOT a specialisation, it's an overloaded function template T identity(Foo x) { return x.foo; } int main() { Foo x = { 42 }; identity(x); } -------------------------------------------------------------------- V Sep 3 '05 #2

 P: n/a Great, thanks :) Alex Sep 3 '05 #3

### This discussion thread is closed

Replies have been disabled for this discussion.