1

In a function template, the type of the parameters are determined by some trait classes, so their type could get quite long like

template<typename A>
void func(typename Traits<A>::some_type_x x1, typename Traits<A>::some_type_x x2);

Is there some way to aliasing these types? My current solution is to introduce another typename in the template parameters

template<typename A, typename X = typename Traits<A>::some_type_x>
void func(X x1, X x2);

But these could potentially let the function caller to provide some invalid arguments, so I wonder if there is a more elegant solution to this problem?

3
  • People don't tend to shorten std::vector<int> a, std::vector<int> b right? But at least you can still make it int.o trait_type_t<A> x1, trait_type_t<A> x2 Commented Feb 24, 2021 at 6:29
  • There's a decltype solution in stackoverflow.com/a/19824531/5267751 which might or might not be shorter... Commented Feb 24, 2021 at 6:31
  • @user202729 Yeah, maybe declaring some helper types is good enough. The decltype solution would only work if the parameters are of the same type. But in my use cases some parameters involve multiple traits, and they share one top level trait. Commented Feb 24, 2021 at 6:44

2 Answers 2

3

You can declare helper type as the type support library does. E.g.

template<class T>
using Traits_x = typename Traits<T>::some_type_x;

Then use it as

template<typename A>
void func(Traits_x<A> x1, Traits_x<A> x2);
Sign up to request clarification or add additional context in comments.

Comments

0
template <typename A, typename X = typename Traits<A>::some_type_x>
void func(X x1, X x2);

has 2 problems:

  • X is now deducible (so default template is mostly useless).
  • As you mentionned, it can be hijacked with func<A, int>(42, 51);

For the first problem, you might use std::type_identity_t:

template <typename A, typename X = typename Traits<A>::some_type_x>
void func(std::type_identity_t<X> x1, std::type_identity_t<X> x2);

and for the second, you might introduce a parameter pack between which would take any extra parameters:

template <typename A, typename..., typename X = typename Traits<A>::some_type_x>
void func(std::type_identity_t<X> x1, std::type_identity_t<X> x2);

But not sure it is better than original though...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.