Nicholas Hamilton
Nicholas Hamilton

Reputation: 10506

Template variable

I can create template functions like this:

template<typename T> T trivialA(T in) { return in; }
template<typename T> T trivialB(T in) { return in; }

// Calculation
int main(int argc, char *argv[]) {
    trivialA<int>(1);
    trivialB<int>(2);
    return 0
}

However, what I would like to do, is something like this (so the user can specify the precision they want):

template<typename T> T trivialA(T in){ return in; }
template<typename T> T trivialB(T in){ return in; }

// Calculation
int main(int argc, char *argv[]) {
    type THETYPE = int; //<<<<<<<<<<<<<<< WHAT IS THE CORRECT WAY TO DO THIS?
    trivialA<THETYPE>(1);
    trivialB<THETYPE>(2);
    return 0;
}

So my question is, how can I hold the datatype as a variable and pass it into my template functions?

Upvotes: 1

Views: 68

Answers (2)

Mooing Duck
Mooing Duck

Reputation: 66922

The old way that you see everwhere is

typedef int THETYPE;
typedef char*(*func_ptr)(int); //declare func_ptr as a pointer to a `char*(int)` function.

The newer more intuitive way:

using THETYPE = int;
using func_ptr = char*(*)(int);

Note that this effectively just makes a new name for a type at compile time, and cannot be changed. Ergo, useless for runtime decisions. If you need to decide at runtime, you'll need to enumerate the possible types and then use an enumeration, and possible type erasure via dynamic polymorphism.

Simple way

template<class T>
void do_stuff() {
    std::cout << 4;
}
enum use_type_enum {use_int, use_float};
int main() {
    use_type_enum use_type;
    std::cin >> use_type;

    switch(use_type) {
    case use_int: do_stuff<int>(); break;
    case use_float: do_stuff<float>(); break;
    default: throw std::runtime_error("incorrect math type");
    }
}

complex but powerful way:

struct math_type {
    virtual ~math_type() {}
    virtual void print() const =0;
};
template<class T>
struct math_type_instance {
    T var;
    math_type_instance(T v) : var(v) {}
    virtual ~math_type_instance () {}
    virtual void print() const {std::cout << var;}
};
enum use_type_enum {use_int, use_float};

int main() 
    use_type_enum use_type;
    std::unique_ptr<math_type> variable;

    std::cin >> use_type;

    switch(use_type) {
    case use_int: variable = make_unique<math_type_instance<int>>(3); break;
    case use_float: variable = make_unique<math_type_instance<float>>(3); break;
    default: throw std::runtime_error("incorrect math type");
    }

    variable->print();
}

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

Use typedef.

typedef int THETYPE;

Upvotes: 0

Related Questions