C++ Template const char array to int

Posted by Levi Schuck on Stack Overflow See other posts from Stack Overflow or by Levi Schuck
Published on 2012-10-03T21:27:02Z Indexed on 2012/10/03 21:37 UTC
Read the original article Hit count: 196

Filed under:
|
|

So, I'm wishing to be able to have a static const compile time struct that holds some value based on a string by using templates. I only desire up to four characters. I know that the type of 'abcd' is int, and so is 'ab','abc', and although 'a' is of type char, it works out for a template<int v> struct

What I wish to do is take sizes of 2,3,4,5 of some const char, "abcd" and have the same functionality as if they used 'abcd'. Note that I do not mean 1,2,3, or 4 because I expect the null terminator.

cout << typeid("abcd").name() << endl; tells me that the type for this hard coded string is char const [5], which includes the null terminator on the end.

I understand that I will need to twiddle the values as characters, so they are represented as an integer.

I cannot use constexpr since VS10 does not support it (VS11 doesn't either..)

So, for example with somewhere this template defined, and later the last line

template <int v> struct something {
    static const int value = v;
};

//Eventually in some method
cout << typeid(something<'abcd'>::value).name() << endl;

works just fine.

I've tried

template<char v[5]> struct something2 {
    static const int value = v[0];
}

template<char const v[5]> struct something2 {
    static const int value = v[0];
}

template<const char v[5]> struct something2 {
    static const int value = v[0];
}

All of them build individually, though when I throw in my test,

cout << typeid(something2<"abcd">::value).name() << endl;

I get

'something2' : invalid expression as a template argument for 'v'
'something2' : use of class template requires template argument list

Is this not feasible or am I misunderstanding something?

© Stack Overflow or respective owner

Related posts about c++

Related posts about string