Priority when choosing overloaded template functions in C++(C++中选择重载模板函数时的优先级)
问题描述
我有以下问题:
class Base
{
};
class Derived : public Base
{
};
class Different
{
};
class X
{
public:
template <typename T>
static const char *func(T *data)
{
// Do something generic...
return "Generic";
}
static const char *func(Base *data)
{
// Do something specific...
return "Specific";
}
};
如果我现在这样做
Derived derived;
Different different;
std::cout << "Derived: " << X::func(&derived) << std::endl;
std::cout << "Different: " << X::func(&different) << std::endl;
我明白
Derived: Generic
Different: Generic
但我想要的是,对于从 Base 派生的所有类,调用特定方法.所以结果应该是:
But what I want is that for all classes derived from Base the specific method is called. So the result should be:
Derived: Specific
Different: Generic
有什么办法可以重新设计 X:func(...)s 来达到这个目标吗?
Is there any way I can redesign the X:func(...)s to reach this goal?
假设 X::func(...) 的调用者不知道作为参数提交的类是否从 Base 派生.所以 Casting to Base 不是一个选项.事实上,整个事情背后的想法是 X::func(...) 应该检测"参数是否来自 Base 并调用不同的代码.出于性能原因,应该在编译时进行检测".
Assume that it is not known by the caller of X::func(...) if the class submitted as the parameter is derived from Base or not. So Casting to Base is not an option. In fact the idea behind the whole thing is that X::func(...) should 'detect' if the parameter is derived from Base or not and call different code. And for performance reasons the 'detection' should be made at compile time.
推荐答案
我找到了一个非常简单的解决方案!
I found a VERY easy solution!
class Base
{
};
class Derived : public Base
{
};
class Different
{
};
class X
{
private:
template <typename T>
static const char *intFunc(const void *, T *data)
{
// Do something generic...
return "Generic";
}
template <typename T>
static const char *intFunc(const Base *, T *data)
{
// Do something specific...
return "Specific";
}
public:
template <typename T>
static const char *func(T *data)
{
return intFunc(data, data);
}
};
这很好用,而且很苗条!诀窍是让编译器通过(否则无用的)第一个参数选择正确的方法.
This works great and is very slim! The trick is to let the compiler select the correct method by the (otherwise useless) first parameter.
这篇关于C++中选择重载模板函数时的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++中选择重载模板函数时的优先级
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01