4

I need to access type information from a class I used to instantiate another class.

Specifically void Beta<T>::do_something() needs to accept parameters of type W, S that were used to instantiate class Alpha<W, S>.

template<typename W, S> 
class Alpha {
public:
  using carry_W = W;
  using carry_S = S;
};

template<typename T> 
class Beta {};
template<typename T>
void Beta<T>::do_something(typename T::carry_W p1, typename T::carry_S p2) {}

Beta<Alpha<int, double>> b;

The solution above works fine but is there any other way to do this without aliasing the types as class members? Is there a more "C++" way of doing this?

Florin Gogianu
  • 338
  • 4
  • 10
  • possible duplicate of [Can one access the template parameter outside of a template without a typedef?](http://stackoverflow.com/questions/3696286/can-one-access-the-template-parameter-outside-of-a-template-without-a-typedef) – m.s. Sep 07 '15 at 08:31
  • 1
    Purely stylistic but I'd rather use something like [this](http://coliru.stacked-crooked.com/a/2dbf6b21987a5a7b) – Marco A. Sep 07 '15 at 08:32
  • Why don't you just take all arguments with forwarding references and let validity inside `do_something` do the rest? – Columbo Sep 07 '15 at 08:33
  • @Columbo not sure I get it, would it be possible to develop this more? – Florin Gogianu Sep 07 '15 at 08:41

2 Answers2

1

You can create a class template that consists only of a forward declaration and a partial specialisation.

#include <iostream>

using namespace std;

template<typename W, typename S> 
class Alpha {
};

template<typename>
class Beta;

template<typename W, typename S, template<typename, typename> class T>
class Beta<T<W,S>> {
public:
  void do_something(W w, S s) {
      cout << w << ", " << s << '\n';
  }
};

int main() { 
    Beta<Alpha<int, double>> b;
    b.do_something(0, 0.0);
}
tahsmith
  • 1,643
  • 1
  • 17
  • 23
0

Do you mean something like the following (template 'pattern matching')?

template<typename T<W, S>>
void Beta<T>::do_something(W, S) {...}

While I think your question is totally legit, I fear that the current C++ does not allow this shortcut...

xtofl
  • 40,723
  • 12
  • 105
  • 192
  • Yes, that would be something I guess. I was asking because the way I wrote it seems to me a bit of a hack and I was not sure if this is the accepted way of doing it. – Florin Gogianu Sep 07 '15 at 10:08