0

I'm having trouble understanding why this code doesn't work when using a double/float. Most results from searching this error give me some sort of linkage error, but the code does sometimes work, so I'm not sure how to change how it's linked.

In a file header.h, I have:

template<typename any>
void validInput(any &myInput, int=std::numeric_limits<int>::max());

This is a function that checks user input to make sure it's valid, and if it is, less than the given int (ex. validInput(variable,5) has the user input a value for variable, and checks if it's between 0 and 5)

I then define my function in a file like functions1.cpp:

#include <iostream>
#include <limits>
#include "header.h"

template<typename any>
void validInput(any &myInput, int maxnum){
    while((!(std::cin>>myInput))||myInput<=0||myInput>maxnum){
    std::cout<<"\nInvalid input.\nEnter new number: ";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
    }
}

Then, in another function, say functions2.cpp , I want to use my validInput function, so I write something like this:

#include <iostream>
#include "header.h"

void className::function(){
    double checkThisValue;
    std::cout << "Enter value to be checked: ";
    validInput(checkThisValue);
}

(I'm purposely not including the second 'int input' because I want it to default to std::numeric_limits<int>::max())

This code gives me the error: undefined reference to 'void validInput<double>(double&,int)'

But if I instead define checkThisValue as an int, then the code compiles and works correctly.

Why can't I pass doubles or floats to my function? How should I properly link the files?

Edit: I can't answer the question because it was closed, but I needed to "explicitly instantiate" the template. The duplicate question deals with classes, so the syntax was a little different. The solution was adding the following line in the functions1.cpp file:

template void validInput<double>(double &myInput, int maxnum);

Emilio Garcia
  • 554
  • 1
  • 5
  • 20

0 Answers0