C++中选择重载模板函数时的优先级 [英] Priority when choosing overloaded template functions in C++

查看:19
本文介绍了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++中选择重载模板函数时的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆