0

When I define many functions which are required to receive more than one type of parameter, I end up using template <typename T> many times, like so:

#pragma once

#include <iostream>
#include <vector>
#include <bitset>
using namespace std;

class Unlint {
    vector<bitset<8>> bitarray;

public:
    template <typename T>
    Unlint(T varx);

    template <typename T>
    Unlint operator + (T varx);

    template <typename T>
    Unlint operator - (T varx);

    //...
};

Repeating code like this feels dirty. Are there any non-repetitive methods?

For context, I'm trying to code Unlint as an int-like object with essentially no limit, for my own practice.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

3

There are a few techniques. Macros are one approach that I've seen, especially in implementations, but they are not well liked by the community, and require some mental parsing that makes code harder to read (and likelier to have bugs.)

In C++20 you have an option to replace your code using a new syntax, with the auto keyword as a placeholder in normal functions. (It was only available in generic lambdas previously.)

class Unlint {
    vector<bitset<8>> bitarray;
public:
    
    Unlint(auto varx);
    Unlint operator + (auto varx);
    Unlint operator - (auto varx);
    //...
};

It is still a template, so the definition must still be known by callers, and the body must be visible before any place it's used. Usually, that means that the definition of the function, especially if it's public, usually ought to go in the header file.

Chris Uzdavinis
  • 6,022
  • 9
  • 16