Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type definitions dependent on template parameters

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:

  1. 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.
  2. An alternative would be to write all the usings into a file and let the compiler do the copy & pasting for me via include. 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.
  3. 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.

like image 870
quantenstau Avatar asked Dec 05 '25 09:12

quantenstau


1 Answers

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&>);
like image 121
passing_through Avatar answered Dec 06 '25 23:12

passing_through



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!