有没有办法在数据成员上使用 decltype 来声明方法参数

问题描述

考虑一些简单的代码

struct A {
  using Type = int;
};

struct B  {
  void test( A::Type i ) { printf("%d\n",i); }
  A a;
};

然而,在实际示例中,“A”是一个很长的模板类型,输入起来并不有趣。即使我确实需要输入它(声明它),我也不想输入两次。即使我在两个地方都做对了,它也是可以改变的,所以维护起来会很头疼。

那么,问题是,如何在不明确提及“A”的情况下向 B::test 声明参数?

我尝试过以下方法

void test( decltype(a)::Type )

但这不起作用,因为“a”未在声明范围内声明。如果我使用 decltype(B::a),我会得到 B 不完整的错误

有没有办法做到这一点?

解决方法

在这些情况下,请创建别名。然后,您可以在类中的任何地方使用它 - 即使在声明 a 时也是如此,因此您无需重新组织类定义中的成员。

struct a_long_template_type_that_is_not_fun_to_type {
  using Type = int;
};

struct B {
  using type_alias = a_long_template_type_that_is_not_fun_to_type;
 
  void test( type_alias::Type i ) { printf("%d\n",i); }
  type_alias a;
};
,

骗我。看起来我需要做的是在方法之前声明数据成员,并且它有效:

struct B {
  A a;
  void test( decltype(a)::Type i ) { printf("%d\n",i); }
};