My problem is that I have no idea how to check if object is const. I can only use C++98. How can I check if object have const modifier? How to overload functions properly?
int main(){
Vec x;
const Vec y;
cout<<"Is x const? ";
y.IfConst(x); // cout << "no"
cout<<"\n";
cout<<"Is x const? ";
x.IfConst(x) // cout << "no"
cout<<"\n";
cout<<"Is y const? ";
x.IfConst(y); // cout << "yes"
cout<<"\n";
cout<<"Is y const? ";
y.IfConst(y); // cout << "yes"
cout<<"\n";
/**/
}
I need output look like: is x const? no is x const? no is y const? yes is y const? yes
I used:
void Vec::IsConst(Vec const &vecc) const{
std::cout << "YES" << std::endl;
}
void Vec::IsConst(Vec const &vecc) {
std::cout << "NO" << std::endl;
}
To check the type of a variable or a constant, you can use the typeof operator followed by the variable name in TypeScript. This is the same method used in the case of vanilla JavaScript code.
Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).
To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition.
The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.
constness is known and used only as compile time, the information doesn't exist at runtime, it has no sense.
However, at compile time, if you have a C++11 compliant compiler, you can use the standard std::is_const
type trait on a type:
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_const<const int>::value << '\n';
std::cout << std::is_const<Vec>::value << '\n';
}
If you don't have a c++11 compiler, you can use boost one.
Your proposed syntax does not make sense to me.
This works for me.
#include <iostream>
template <typename T> bool isConst(T& x)
{
return false;
}
template <typename T> bool isConst(T const& x)
{
return true;
}
int main()
{
int x;
const double y = 0.0;
std::cout << "Is x const? ";
std::cout << isConst(x) << "\n";
std::cout << "Is y const? ";
std::cout << isConst(y) << "\n";
}
Output:
Is x const? 0 Is y const? 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With