Partial specialisation of method taking parameterized parameter

  • Thread starter =?iso-8859-1?q?Erik_Wikstr=F6m?=
  • Start date
?

=?iso-8859-1?q?Erik_Wikstr=F6m?=

I'd like to create a partial specialization of a member-method of a
parameterized class which takes a parameterized argument, but I'm not
sure if it's possible or, if possible, how. The following code
demonstrates what I'd like to to:

#include <iostream>

template<class T>
struct BarA
{
void bar() { std::cout << "BarA\n"; }
};

template<class T>
struct BarB
{
void bar() { std::cout << "BarB\n"; }
};

template<class T>
struct Test
{
template<template<class U = T> class V>
void foo(V<T>& f);
};

template<class T>
template<template<class> class V>
void Test<T>::foo(V<T>& f)
{
f.bar();

}

/* A partial specialization that prepends the output of f.bar() with
"BarB: "
template<class T>
template<>
void Test<T>::foo(BarB<T> f)
{
std::cout "BarB: ";
f.bar();
}
*/

int main()
{
BarA<int> a;
BarB<int> b;

Test<int> t;
t.foo(a);
t.foo(b);
}

This should, print:
BarA
BarB: BarB

Any help appreciated.
 
D

dasjotre

Erik said:
template<class T>
struct Test
{
template<template<class U = T> class V>
void foo(V<T>& f);

void foo(BarB said:
};

template<class T>
template<template<class> class V>
void Test<T>::foo(V<T>& f)
{
f.bar();

}

template<class T>
void Test<T>::foo(BarB<T> & f)
{
std::cout << "BarB: ";
f.bar();
}
 
V

Victor Bazarov

Erik said:
I'd like to create a partial specialization of a member-method [..]

You can stop right there. C++ does not allow partial specialisations
of function templates. Another mistake: you cannot specialise any
member without first specialising the class template.

The specification you gave in the form of your [non-compiling] code
is a bit unclear. Are you trying to make your 'foo' member have
a different behaviour if the template for which it's instantiated is
'BarB' (versus any other)? It is very likely you need a helper class
template for that. You can then specialise your helper template:

template<class T> struct TestHelper {
static void help() {} // do nothing for all
};

template<class T> sturct TestHelper<BarB<T> > {
static void help() { std::cout << "BarB: "; }
};

template<class T> struct Test {
template<template<class> class B> void foo(B<T> f) {
TestHelper<B<T> >::help(); ///////////////////// some help
f.bar();
}
};

V
 

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

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top