I am currently working with template classes in C . In these classes, I am using types that are again dependent on the template parameters. In order to not type the parameters all the time, I did something along the lines of
template<typename T>
class A
{
using someName = someClass<T>;
}
There are some more examples in the actual code but this should illustrate the idea.
This worked fine, as long as I only needed someName
in class A
. But my project has since grown and I have added other templated classes that should use someName
as well.
My question is: What is the best way to define (several) types as above that depend on some template parameters and use them in multiple other classes (at best without having the write out all of the parameters constantly)?
My ideas so far:
- Of course, I can simply copy
using someName = std::someClass<T>;
to all the classes using it. But this is not very elegant and both adding classes and adding such types becomes increasingly cumbersome. - An alternative would be to write all the
using
s into a file and let the compiler do the copy & pasting for me viainclude
. But I am not sure whether this would actually work and it seems to be a very brute force approach and in general not good practice. - I also tried different approaches involving
using
but none of them worked so far. Still, it seems to me that this might be the most promising route to the solution.
Maybe I am making things way too complicated and there is an easier and more straightforward solution to this.
CodePudding user response:
Create a struct which defines each common alias:
template<typename T> struct Aliases {
using value_type = T;
using reference = T&;
};
...and inherit from it:
template<typename T> class Foo: public Aliases<T> {};
template<typename T> class Bar: public Aliases<T> {};
template<typename T> class Baz: public Aliases<T> {};
Some tests:
static_assert(std::same_as<Foo<char>::value_type, char>);
static_assert(std::same_as<Bar<int>::reference, int&>);
static_assert(std::same_as<Baz<int>::reference, int&>);