Search code examples
c++decltype

Is there a way to use decltype on a data member to declare a method argument


Consider some simple code:

struct A {
  using Type = int;
};

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

In real example, however, "A" is a long, template type that's not fun to type. Even though I do need to type it (to declare it), I don't want to have to type it twice. Even if I got it right in both places, it's the sort of thing that can change, so it would be a maintenance headache.

So, the question is, how can I declare the argument to B::test without explicitly mentioning "A"?

I've tried things like:

void test( decltype(a)::Type )

but that doesn't work because "a" isn't declared in the scope of the declaration. If I use decltype(B::a), I get the error that B is incomplete.

Is there a way to do this?


Solution

  • In these cases, make an alias. You then get to use it everywhere in your class - even when declaring a, so you don't need to reorganize the members in your class definition.

    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;
    };