lundi 28 mars 2016

C++ Calling template specialized function

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.

Aucun commentaire:

Enregistrer un commentaire