简体   繁体   中英

Can I use templates with this syntax?

I found this StackOverflow question while looking for some sort of way to abstract data types.

I wanted to create an IO helper function that takes as parameters a class(more often than not a string) and a data type.

I'm also doubting the variable y part. I don't know if the syntax is correct if I wanted y's value to change.

template <class message>
template <typename variable>
void inputCheck(message x, variable y)
{
    cout << x;
    cin >> y;
    // if input y is invalid, call inputCheck again
    // else, keep the input and assign it to y located outside this function
}
template <class OutputType, class InputType>
void InputCheck(const OutputType &x, InputType &y) {
  cout << x;
  cin >> y;
}

Also pay attention at InputType &y : y needs to be passed as a referenced so that its modification can be seen outside the function.

x is passed as const & because if OutputType is large (a struct, a string or a vector etc.) passing by reference is way faster. The const assures that it won't be modified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM