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
Bytes IT Community
+ 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 <class T> 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 <class T>
struct Foo {
T foo;
};

Is there any way I can do something like the following?

template <>
template <class FooT> // Parameter for Foo; not legal C++ code.
Foo<T> identity(T x) { return x.foo; }

Any help would be appreciated.

Thanks,
Alex

Sep 3 '05 #1
Share this Question
Share on Google+
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 <class T> 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 <class T>
struct Foo {
T foo;
};

Is there any way I can do something like the following?

template <>
template <class FooT> // Parameter for Foo; not legal C++ code.
Foo<T> identity(T x) { return x.foo; }

Any help would be appreciated.


Just define an overloaded function:
--------------------------------------------------------------------
template <class T> T identity(T x) { return x; }

template <class T>
struct Foo {
T foo;
};

// the following is NOT a specialisation, it's an overloaded function
template<class T> T identity(Foo<T> x) { return x.foo; }

int main() {
Foo<int> 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.