gpt4 book ai didi

c++ - 将抽象类继承与实例化模板混合

转载 作者:太空宇宙 更新时间:2023-11-04 11:30:13 27 4
gpt4 key购买 nike

好的,我知道 - 主要是由于复杂性 - 虚拟模板方法是不允许的。

但是,考虑到这一点:

// something.h

class absClass
{
public:
// ...
// instead of templating the absClass fun method, define the different
// overloads that are going to be used:
virtual void fun(classA a) = 0;
virtual void fun(classB b) = 0;
};

class impClass : public absClass
{
public:
// ...
template <typename T>
void fun(T t)
{ /* whatever */ }

// declaration
void fun(classA a);
void fun(classB b);
};

然后我们在impClass中建立方法的具体实例化?

// something.cpp
#include "something.h"

// instantiation
void impClass::fun<classA>(classA t);
void impClass::fun<classB>(classB t);

这不是应该的吗?我收到错误(无论它们是在 .h 还是 .cpp 中实例化)。

最佳答案

// ---- something.h
class absClass
{
public:
// ...
// instead of templating the absClass fun method, define the different
// overloads that are going to be used:
virtual void fun(classA a) = 0;
virtual void fun(classB b) = 0;
};

class impClass : public absClass
{
public:
// ...
template <typename T>
void fun(T t)
{
/* whatever */ #1
}

// declaration
void fun(classA a)
{
// #2 -- the implementation of base class pure virtual function
// Note: you must define this function, otherwise there is linker error
}
void fun(classB b)
{
}
};

// ---- something.cpp
#include "something.h"

// instantiation
template void impClass::fun<classA>(classA t); // add missing "template"
template void impClass::fun<classB>(classB t); // add missing "template"

// ---- main.cpp
impClass o;
classA a;
o.fun<classA>(a); // calls #1
o.fun(a); // calls #2

既然你在写 void impClass::fun<classA>(classA t);那么你正在做特化,所以你需要添加 template<>在此之前。

但这不是您实现虚函数的函数体,它们是其他东西...检查我提供的 2 个不同的调用。


编辑#1,基于评论:

好吧,如果你想为特定类(class)取得一些特别的成就,那么特化还是有意义的,对吧?

那么实例化的意义何在?您是否正在尝试导出类模板?


编辑#2,基于评论:

这是你想要的吗?

class impClass : public absClass
{
public:
template <typename T>
void so_fun(T t)
{
/* whatever */
/* define the common behavior here */
}
void fun(classA a)
{
so_fun(a);
}
void fun(classB b)
{
so_fun(b);
}
};

或:

template <typename T>
void so_fun(T t)
{
/* whatever */
/* define the common behavior here */
}

class impClass : public absClass
{
public:
void fun(classA a)
{
so_fun(a);
}
void fun(classB b)
{
so_fun(b);
}
};

关于c++ - 将抽象类继承与实例化模板混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25072835/

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