Search code examples
c++decltype

For the code below, I changed decltype(s1.size()) to int and the code worked just fine. Is decltype(s1.size()) redundant in this context?


I'm new to C++. I'm trying to learn the concept of decltype. I saw this code online. I changed decltype(s1.size()) to int and the code worked just fine. Is decltype(s1.size()) redundant in this context or is there something I'm missing?

int main(){
    string s1 = "hello world";
    decltype(s1.size()) a = 0;
    while ( a < s1.size()){
        s1[a++] = 'x';
        cout << s1 << endl;
    }
}

Why decltype is needed here, int works the same?


Solution

  • Is decltype(s1.size()) redundant in this context?

    I wouldn't use "redundant". To me, redundant means superfluous, i.e. specifying something that is already specified or need not be specified.

    Perhaps you are thinking of "unnecessarily complicated".

    Regardless, it is helpful to use decltype when you don't necessarily remember the return type of a function and you want to create more than one instances of the type. Also remember that you can use auto to deduce the type of an object from the expression used to initialize it.

    You could use:

    // Make the type of a to be deduced from the return type of s1.size()
    auto a = s1.size();
    

    and

    // Define a type based on the return type of s1.size()
    using size_type = decltype(s1.size());
    
    // Use the type.
    size_type a = s1.size();
    size_type b = 0;
    for ( ; b < a; ++b )
    {
       ...
    }
    

    and

    // Make the type of a to be deduced from the return type of s1.size()
    auto a = s1.size();
    
    // Make the type of b to be the same as the type of a.
    decltype(a) b = 0;
    for ( ; b < a; ++b )
    {
       ...
    }
    

    More on the subject: https://stackoverflow.com/search?q=[cpp]+decltype+is%3Aq.