How do I prevent size_t from being interpreted as a reference?
source link: https://www.codesd.com/item/how-do-i-prevent-size-t-from-being-interpreted-as-a-reference.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How do I prevent size_t from being interpreted as a reference?
How can I change the signature of distanceTo(..)
to make the compiler warn or error on a call with std::size_t
as parameter?
class Point {
private:
float value;
public:
Point(float value) : value(value){};
float distanceTo(const Point &point) { return point.value - value; }
};
int main() {
std::size_t index = 1;
Point start(1);
Point end(4);
float dist = start.distanceTo(index); // compiles, but should not!
std::cout << dist;
return 0;
}
Make the constructor explicit
:
explicit Point(float value) : value(value) {} // no semicolon here
This disallows implicit conversions (from size_t
through float
to Point
), but note that it also makes code such as start.distanceTo(3.14)
and Point p = 3.14;
invalid.
Related Articles
How can I prevent AsyncTask from being run repeatedly in the onScroll event?
How can I prevent SoapExtensions from being added to my Web service application?
How to omit / prevent data from being sent to the POST method in the controller in MVC
How do I prevent symbols from being stored in the database using php?
How can I prevent text from being selected?
How do I prevent transactions from being blocked in the sql server for all connections?
Flex mx: axisrenderer How can I prevent labels from being scaled
How can I prevent iBeacons from being tampered with?
How can I prevent objects from being instantiated except in a defined "factory class"?
How do you prevent collisionists from being passed on to each other?
How can I prevent Objects from being released when using Objective-C ARC with Xcode 4.2?
How do you prevent functions from being excluded from the coverage profile?
When you edit the UIButton label, how can I prevent it from being shortened by using '& hellip;'?
How can I prevent objects from being blurred in a canvas?
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK