gpt4 book ai didi

c++ - 在派生类中作为模板实现的虚函数

转载 作者:搜寻专家 更新时间:2023-10-30 23:55:40 24 4
gpt4 key购买 nike

有以下代码:

struct Base
{
virtual void print(int x) = 0;
virtual void print(float x) = 0;
};

struct Derived : public Base
{
template<typename T>
void print(T x)
{
std::cout<<x<<std::endl;
}
};

是否有可能做一些 C++ 黑魔法(对这些类型进行显式实例化,一些智能 using 等)来识别以下实现:

virtual void print(int x) = 0;
virtual void print(float x) = 0;

Derived类中的形式为:

template<typename T>
void print(T x)

最佳答案

不,没有。

您可以做的是转发到本地模板实现:

struct Derived : public Base
{
void print(int x) override { printTempl(x); }
void print(float x) override { printTempl(x); }

template <typename T>
void printTempl(T x)
{
std::cout << x << std::endl;
}
};

如果你觉得太冗长,而且你有很多这样的 print,你也可以宏它:

#define PRINT_FWD(typ) void print(typ x) override { printTempl(x); }

关于c++ - 在派生类中作为模板实现的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30923902/

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