gpt4 book ai didi

C++调用模板专用函数

转载 作者:行者123 更新时间:2023-11-28 05:45:41 24 4
gpt4 key购买 nike

我有以下一段代码。代码编译正常:

文件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"

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

What is the type in : const std::shared_ptr<B>& b

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

关于C++调用模板专用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36265582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com