0

If it is possible, how could I avoid to write twice template < typename T> above my 2 functions making them still work for every argument type thew would have to work with?

And, even if it is possible, how could I write only the reverse_vector function making it contain "inside" the swap function, so I could be able to write template only once?

(I'm still a beginner learning basics and I absolutely don't know if there are better ways to do what I think you have understood I'd like. If yes, please say those. Thank you so much, good evening.)

#include <iostream>
#include <vector>

template <typename T>//HERE...
void swap(T& a, T& b) {
    T tmp = a;
    a = b;
    b = tmp;
}

template <typename T>//...AND HERE
void reverse_vector(std::vector<T>& v) {
    if (v.size() % 2 == 0) {
        for (T i = 0; i < v.size() / 2; ++i) {
            swap(v[i], v[v.size() - 1 - i]);
        }
    }
}

void print_vector(std::vector<short int>& v) {
    for (unsigned short int i = 0; i < v.size(); ++i) {
        std::cout << v[i] << '\n';
    }
}

int main() {
    unsigned short int g;
    std::cout << "How large do you want the vector? _";
    std::cin >> g;

    std::vector <short int> v(g);

    for (unsigned short int i = 0; i < g; ++i) {
        v[i] = i + 1;
    }

    print_vector(v);
    std::cout << "\n\n\n";

    reverse_vector(v);
    print_vector(v);

    return 0;
}
thomas
  • 111
  • 8
  • Each of those is a template-function. As such, each requires a template declaration to *some* degree. You *could* implement `swap` inside your reverse function as a lambda, and thereby reap `T` accordingly. – WhozCraig Mar 12 '22 at 17:50
  • The short answer is you can not do this! – zain ul din Mar 12 '22 at 17:54
  • But In lambdas, you can use auto keyword instead of templates – zain ul din Mar 12 '22 at 17:55
  • 2
    C++20 permits `swap(auto& a, auto& b)`. [see this answer](https://stackoverflow.com/a/60355539/1563833) – Wyck Mar 12 '22 at 18:07
  • In reverse_vector you are using T once for the index, once for the value type of the vector. Is the template line such a problem? – Sebastian Mar 12 '22 at 19:08

1 Answers1

1

You can not write template <typename T> only once. But you can write it not at all with c++20:

#include <concepts>

void swap(auto a, auto b) requires std::same_as<decltype(a), decltype(b)> {
  auto tmp = a;
  a = b;
  b = tmp;
};

The requires clause is there to make sure you don't accidentally swap something of different types. I probably just broke the whole semantic and make swap copy everything. Think whether you need auto, auto&, auto&& to get the right semantic for swap before you use it.

PS: use std::ranges::swap

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42