non-member function cannot have cv-qualifier

C++TemplatesConstants

C++ Problem Overview


While writing the following function abs, I get the error:

non-member function unsigned int abs(const T&) cannot have cv-qualifier.

template<typename T>
inline unsigned int abs(const T& t) const
{
    return t>0?t:-t;
}

After removing the const qualifier for the function there is no error. Since I am not modifying t inside the function the above code should have compiled. I am wondering why I got the error?

C++ Solutions


Solution 1 - C++

Your desire not to modify t is expressed in const T& t. The ending const specifies that you will not modify any member variable of the class abs belongs to.

Since there is no class where this function belongs to, you get an error.

Solution 2 - C++

The const modifier at the end of the function declaration applies to the hidden this parameter for member functions.

As this is a free function, there is no this and that modifier is not needed.

The t parameter already has its own const in the parameter list.

Solution 3 - C++

The cv-qualifier on a member function specifies that the this pointer is to have indirected type const (or volatile, const volatile) and that therefore the member function can be called on instances with that qualification.

Free functions (and class static functions) don't have a this pointer.

Solution 4 - C++

As we all know, const keyword followed after the argument list indicates that this is a pointer to a pointer constant.

There is a non-member function, it does not belong to the class, so add const opposite end error occurs.

Solution to the problem: is to either become a class member function or remove the const keyword const opposite end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionA. K.View Question on Stackoverflow
Solution 1 - C++AttilaView Answer on Stackoverflow
Solution 2 - C++Bo PerssonView Answer on Stackoverflow
Solution 3 - C++ecatmurView Answer on Stackoverflow
Solution 4 - C++Xiaofeng.WangView Answer on Stackoverflow