Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template : no matching function for call

Tags:

c++

templates

Consider the following code

template <typename T, T one>
T exponentiel(T val, unsigned n) {
    T result = one;
    unsigned i;
    for(i = 0; i < n; ++i)
        result = result * val;

    return result;
}

int main(void) {

    double d = exponentiel<double,1.0>(2.0f,3);

    cout << d << endl;

    return 0;
}

The compiler tells me this no matching function for call to 'exponentiel(float, int)'

Why?

What's strange is that exponentiel works with int.

like image 636
Justin Avatar asked Dec 29 '22 00:12

Justin


1 Answers

The problem is with the T one and the 1.0 in the template argument list.

You can't have a nontype template parameter of a floating point type and you can't pass a floating point value as a template argument. It's just not allowed (to the best of my knowledge, there's no really good reason why it's not allowed).

g++'s error message here is rather unhelpful. Visual C++ 2010 reports the following on the line where the template is used in main:

error C2993: 'double' : illegal type for non-type template parameter 'one'

Comeau Online reports:

line 13: error: expression must have integral or enum type
    double d = exponentiel<double,1.0>(2.0f,3);
                                  ^

line 2: error: floating-point template parameter is nonstandard
    template <typename T, T one>
                          ^
like image 137
James McNellis Avatar answered Jan 10 '23 00:01

James McNellis