如果参数包右侧包含简单类型参数,为什么可变参数模板参数包保持相同的大小?

问题描述

为了在可变参数模板中找到类型的位置,我实现了以下模板:

template <class T,class ...Params,class Based>
size_t derived_index(Based* a) {
  // show template instance and size of Params
  std::cout << __PRETTY_FUNCTION__ << std::endl;
  std::cout << sizeof...(Params) << std::endl; 
  
  // verify is a is one of the polymorphic types 
  if (dynamic_cast<T*>(a) != nullptr)
    return 0;
  else 
    return 1u + derived_index<Params...,Based>(a);
}

以这种方式可以推导出Based模板参数,例如:

struct Base { virtual void f() = 0; };
struct A: Base { void f() override {} };
struct B: Base { void f() override {} };
struct C: Base { void f() override {} };
struct D: Base { void f() override {} };

int main() {
  Base* a = new A;
  Base* c = new C;
  std::cout << " index: " << derived_index<A,B,D>(c) << std::endl;
  return 0;
}

我做了另一个看起来更好的实现,因为它检测是否找不到并返回-1,所以我需要重载derived_index

UPDATED VERSION 这个可以很好地推断出基于类型。

template <class Based>
int derived_index(Based* a) {
  std::cout << __PRETTY_FUNCTION__ << std::endl;
  return -1;
}

template <class T,class Based>
int derived_index(Based* a) {
  std::cout << __PRETTY_FUNCTION__ << std::endl;
 
  if (dynamic_cast<T*>(a) != nullptr)
    return 0;
  else {
    auto&& index = derived_index<Params...>(a); 
    return  index >= 0 ? 1 + index: -1;
  }
}

在第一个版本 Params 大小保持不变,有人知道这是什么原因吗?标准吗?

谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)