2

Why the compiler fails to infer template argument in the following code? How can I fix the code? I want add as low runtime overhead as possible.

#include <iostream>

using namespace std;

struct Test
{
    template<int N>
    Test(const char data[N]) :
        data(data),
        size(N)
    {}

    const char *data;
    int size;
};

int main()
{
    Test test("Foobar");
    return 0;
}

I tried to make the snippet as small and readable as possible.

pos-reply UPDATE:

This explanation from Tales of C++ K-ballo might be useful:

Lvalue transformations, applied when an lvalue argument is used in context where an rvalue is expected. Those transformations are lvalue to rvalue conversion, array to pointer conversion, and function to pointer conversion. This is the type conversion applied to all function arguments when passed by value, and it is customary referred to as argument decay.

4

1 回答 1

9

You need to accept the argument by reference:

Test(const char (&data)[N] ) 

Now N will be inferred.

In your case, the argument is accepted by value which causes the array to decay to pointer to the first element of the array when it gets passed to the constructor.

于 2013-03-09T18:24:40.183 回答