开发者

C++ template : no matching function for call

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 开发者_StackOverflow中文版= 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.


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>
                          ^
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜