Specializing on a templated type

A

Alex Drummond

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
 
V

Victor Bazarov

Alex said:
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);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top