繁体   English   中英

C ++调用模板专用功能

[英]C++ Calling template specialized function

我有以下代码。 该代码可以很好地编译:

文件啊

#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"

文件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;
}

文件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);
}

输出:

Foo templatized
Foo templatized

我有两个问题:

(1)如何调用模板函数foo的专用版本。

(2)我有

 template <B&, C&>
 void foo(T1 t, const std::shared_ptr<B>& b, const std::shared_ptr<C>& c);

什么是类型:

const std::shared_ptr<B>& b
                      --

是吗

B& or B.
template <B& /*unnamed*/, C& /*unnamed*/>
void foo(T1 t, const std::shared_ptr<B>& b, const std::shared_ptr<C>& c);

foo的重载,而不是专业化。

可以通过指定不可推论的引用来调用它:

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);
}

什么是类型: const std::shared_ptr<B>& b

B不是模板参数,而是一个类。 所以B B类。

因为B和C是普通类,所以在专业化中不需要模板参数

类定义:

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); 
};

和重载:

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;
}

可以

而且,如果您希望重载适用于每种类型的共享指针,则可以执行以下操作:

class A
{
    // ...
    template <class T2, class T3>
    void foo(T1 t1, const shared_ptr<T2>& t2, const shared_ptr<T3>& t3);
};

A·inh

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM