rohitt
rohitt

Reputation: 1215

is a string converted to const char* in C++

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")?

Upvotes: 0

Views: 162

Answers (2)

Martin Morterol
Martin Morterol

Reputation: 2870

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

Upvotes: 3

MSalters
MSalters

Reputation: 179789

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.

Upvotes: 4

Related Questions