Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Syntax in C++

Tags:

c++

templates

I don't understand templates really and was trying to run a simple find the minimum for ints, doubles, chars.

First question, why is template<typename T> sometimes used, and other times template<>?

Second question, I do not know what I am doing wrong with the following code below:

#include <iostream>

template <typename T>
T minimum(T arg1, T arg2)
{
    return arg1 < arg2 ? arg1 : arg2;
}

template <typename T>
// first I tried template <> instd of above, but wasn't sure the difference
T minimum<const char *>(const char *arg1, const char *arg2)
{
    return strcmp(arg1, arg2) ? arg2 : arg1;
}

int main()
{
    std::cout << minimum<int>(4, 2) << '\n';
    std::cout << minimum<double>(2.2, -56.7) << '\n';
    std::cout << minimum(2.2, 2) << '\n';
}

Compile Errors:
 error C2768: 'minimum' : illegal use of explicit template arguments
 error C2783: 'T minimum(const char *,const char *)' : could not deduce template argument for 'T'
 : see declaration of 'minimum'
 : error C2782: 'T minimum(T,T)' : template parameter 'T' is ambiguous
 : see declaration of 'minimum'

Third, in getting familiar with separating .h and .cpp files, if I wanted this minimum() function to be a static function of my class, but it was the only function in that class, would I have to have a template class as well? I originally tried doing it that way instead of having it all in one file and I got some compile errors as well that I can't remember right now and was unsure how I would do that. Thanks!

like image 838
Crystal Avatar asked Jul 31 '26 06:07

Crystal


1 Answers

It sounds like you need to get (and study) a book the covers templates -- it looks like you need to learn far too much of the basics to cover in an answer here.

The template<> syntax is used for template specialization. For what you apparently want, you'd do something like this:

template <class T>
T minimum(T const &a, T const &b) {
    return a < b ? a : b;
}

template<>
char const *minimum<char const *>(char const *a, char const *b) { 
    return strcmp(a, b) ? a : b;
}

Generally speaking, however, this is really the wrong thing to do -- instead of providing specializations for char const *, you usually want to just use std::string, which provides an operator< so your first version would work.

like image 173
Jerry Coffin Avatar answered Aug 01 '26 21:08

Jerry Coffin