String literal pattern argument output

Consider this simple function.

template<typename T>
void func(const T& x) {std::cout<< typeid(T).name();}

Now, if I call the function func("ddd"), what funcdoes T output ?, if there was no parameter in it const, Tit would be easy char [4], then I am confused by the addition const, which displays T on?

: const char [4]. If I change the parameter to T const &x(i.e., the order of change const), then the output produces Tup to char const [4]?

Can someone explain the output of the argument with string literals?

+4
source share
3 answers

String literals are arrays of const characters.

A reference to a 4-character string literal is of type char const (&)[4].

const char [4]and char const [4]- the same types!

char const (&)[N], const char [N] char const [N] char const [N]

#include <iostream>

template<typename T>
void func1(T& x) {std::cout<< typeid(T).name()<<std::endl;}

template<typename T>
void func2(const T& x) {std::cout<< typeid(T).name()<<std::endl;}

template<typename T>
void func3(T const &x) {std::cout<< typeid(T).name()<<std::endl;}

int main()
{
    char c[4]= {'a','b','c','d'};
    const char c1[4]= {'a','b','c','d'};
    char const c2[4]= {'a','b','c','d'};

    func1("abcd"); //prints char const [4]
    func1(c); //prints char [4]
    func1(c1); //prints char const [4]
    func1(c2); //prints char const [4]

    func2("abcd"); //prints char const [4]
    func2(c); //prints char [4]
    func2(c1); //prints char const [4]
    func2(c2); //prints char const [4]

    func3("abcd"); //prints char const [4]
    func3(c); //prints char [4]
    func3(c1); //prints char const [4]
    func3(c2); //prints char const [4]

    return 0;
}
+1

, func(), T ?

, T char const[N].

func , T char [4]

, T& x, no: T char const[N], .

, func , : T const.

T const & x

, const T & - T const &.

0

const , :

char const * - char

char * const - char

char const * const - char

char Foo::bar() const - -, char

and etc.

The host constis an exception related to the early days of C:

const char * <=> char const *

So, changing the order in the template would not change the type at all ( T const &<=> const T &).

If you want to be compatible with the placement const, use only the trailing type, because this is the only way to place constsequentially.

0
source

Source: https://habr.com/ru/post/1608269/


All Articles