Reputation: 1073
I have the following piece of code. The code compiles fine:
File A.h
#include <memory>
class B {};
class C {};
template <class T1>
class A
{
public:
explicit A(T1 t1);
template <class T2, class T3>
void foo(T1 t, T2 t2, T3 t3);
template <B&, C&>
void foo(T1 t, const std::shared_ptr<B>& b, const std::shared_ptr<C>& c);
};
#include "A-inl.h"
File A-inl.h
#include <iostream>
#include <memory>
template <class T1>
A<T1>::A(T1 t)
{
}
template <class T1>
template <class T2, class T3>
void A<T1>::foo(T1 t, T2 t2, T3 t3)
{
std::cout << "Foo templatized" << std::endl;
}
template <class T1>
template <B&, C&>
void A<T1>::foo(T1 t, const std::shared_ptr<B>& b, const std::shared_ptr<C>& c)
{
std::cout << "Foo specalized" << std::endl;
}
File main.cpp:
#include <iostream>
#include<memory>
#include "A.h"
class X{};
class Y{};
class Z{};
int
main()
{
X x;
A<X> a(x);
Y y;
Z z;
a.foo(x, y, z);
const std::shared_ptr<B> b = std::make_shared<B>(B());
const std::shared_ptr<C> c = std::make_shared<C>(C());
a.foo(x, b, c);
}
Output:
Foo templatized
Foo templatized
I had two questions:
(1) How do I make the call to the specialized version of the template function foo.
(2) I have
template <B&, C&>
void foo(T1 t, const std::shared_ptr<B>& b, const std::shared_ptr<C>& c);
What is the type in :
const std::shared_ptr<B>& b
--
Is it
B& or B.
Upvotes: 0
Views: 256
Reputation: 649
Because B and C are ordinary classes, you dont need template parameters in specialisation
class definition:
template <class T1>
class A
{
public:
explicit A(T1 t1);
template <class T2, class T3>
void foo(T1 t, T2 t2, T3 t3);
void foo(T1 t, const std::shared_ptr<B>& b, const std::shared_ptr<C>& c);
};
and overloading:
template <class T1>
void A<T1>::foo(T1 t, const std::shared_ptr<B>& b, const std::shared_ptr<C>& c)
{
std::cout << "Foo specalized" << std::endl;
}
works ok
And if you want your overload to work for shared pointers of every type you can do:
A.h
class A
{
// ...
template <class T2, class T3>
void foo(T1 t1, const shared_ptr<T2>& t2, const shared_ptr<T3>& t3);
};
A-inl.h
template <class T1>
template <class T2, class T3>
void A<T1>::foo(T1 t1, const shared_ptr<T2>& t2, const shared_ptr<T3>& t3)
{
std::cout << "Foo specalized" << std::endl;
}
Upvotes: 0
Reputation: 217573
template <B& /*unnamed*/, C& /*unnamed*/>
void foo(T1 t, const std::shared_ptr<B>& b, const std::shared_ptr<C>& c);
is an overload of foo
, not a specialization.
It can be called by specifying the non-deducible reference:
static B globalB;
static C globalC;
int
main()
{
X x;
A<X> a(x);
Y y;
Z z;
a.foo(x, y, z);
const std::shared_ptr<B> b = std::make_shared<B>(B());
const std::shared_ptr<C> c = std::make_shared<C>(C());
a<globalB, globalC>.foo(x, b, c);
}
What is the type in :
const std::shared_ptr<B>& b
B
is not a template parameter, but a class. so B
is the class B
.
Upvotes: 1