On 4/30/2015 10:27 AM, Juha Nieminen wrote:
> Consider this:
>
> //------------------------------------------------------------------------
> template<typename T> void foo(const T&) { std::printf("Generic\n"); }
> template<> void foo(const char* const&) { std::printf("const char*\n"); }
>
> int main()
> {
> foo(12);
> foo("abc");
> const char* str = "abc";
> foo(str);
> }
> //------------------------------------------------------------------------
>
> It prints:
>
> Generic
> Generic
> const char*
>
> What would be the best way to specialize a template for string literals?
String literals are arrays of char, which do decay to pointers but not
for the purpose of type deduction. I think you should be able to make
this work:
template<typename T> void foo(const T&) { std::printf("Generic\n"); }
template<int n> void foo(const char(&)[n])
{ std::printf("array of const char\n"); }
int main()
{
foo(12);
foo("abc");
const char* str = "abc";
foo(str);
}
The problem, of course, is that literals of different lengths the
compiler will instantiate all different 'foo<n>' variations. You could
try to involve inheritance to unify those.
V
--
I do not respond to top-posted replies, please don't ask