Go Down

Topic: String literal length as template parameter (Read 55 times) previous topic - next topic


I want to do something like this:

Code: [Select]

template<size_t n>
struct arrayReturn {
int arr[n];

auto createArray(const char* input) -> arrayReturn<strlen(input) + 1> {
arrayReturn<strlen(input) + 1> temp;
         // copy char* to arr

        return temp;

or at least something like that, to create a sized int array from a string literal. However, this program is failing to compile because it says strlen(input) +1 cannot be evaluated at compile time. Is there a way I can compute the string literals size at compile time?


There is no way. Template argument must be resolved at compile time so the compiler can generate the correct function/class.
Remember that template is not code; it is a recipe so the compiler can cook code from.

Go Up