0

A string like "hello" would be string or const char*. Consider an example:

template<typename A>
A s(A a){
    // ...
}

here what would be "hello" converted to, if I called s("hello")?

rohitt
  • 1,124
  • 6
  • 18
  • 5
    In C++ all literal strings are really constant arrays of characters (including the null-terminator). As any other array it can decay to a pointer to its first element. It will *never* automatically be converted to a `std::string`. – Some programmer dude Mar 16 '21 at 07:42

2 Answers2

4

A string like "hello" is a const char[6]. Since you can't pass an array by value, A will be deduced to const char* instead.

MSalters
  • 173,980
  • 10
  • 155
  • 350
3

When you are looking for a type you may use this trick :

Create a struct without implementation

template<typename A>
struct Error;

And use it :

template<typename A>
A s(A a){
    Error<A> error;
    return a;
}

int main()
{
    Error<decltype("error")> e; // error: implicit instantiation of undefined template 'Error<char const (&)[6]>'
    s("hello"); // error: implicit instantiation of undefined template 'Error<const char *>'
}

The error will give you the type you are looking for.

Tada! "Hello" type is char const [6] but in the s the decuce type is const char *


Credit :

Effective Modern C++, Chapter 1. Deducing Types, Item 4: Know how to view deduced types.

https://www.oreilly.com/library/view/effective-modern-c/9781491908419/ch01.html

Martin Morterol
  • 2,560
  • 1
  • 10
  • 15
  • 1
    Except that the answer is wrong - `"Hello"` type is not a `const char*`, but `const char[6]`. The link you provided explicitly warns against this mistake. – MSalters Mar 16 '21 at 08:25
  • Edited, better now ? – Martin Morterol Mar 16 '21 at 09:04
  • 1
    Correct - this gives both answers. https://stackoverflow.com/questions/30293262/why-does-decltype-on-a-string-literal-not-yield-an-array-type explains why `decltype` gives that `(&)` bit in the first error message – MSalters Mar 16 '21 at 10:25