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.
相关文章