Make All Types Constant by Default in C++
Asked Answered
P

5

15

What is the simplest and least obtrusive way to indicate to the compiler, whether by means of compiler options, #defines, typedefs, or templates, that every time I say T, I really mean T const? I would prefer not to make use of an external preprocessor. Since I don't use the mutable keyword, that would be acceptable to repurpose to indicate mutable state.

Edit: Since the intent of this was mistaken entirely (and since I wasn't around for a few hours to clarify), let me explain. In essence, I just want to know what systems are available for manipulating the type system at compile time. I don't care if this creates nonstandard, bad, unmaintainable, useless code. I'm not going to use it in production. It's just a curiosity.

Potential (suboptimal) solutions so far:

// I presume redefinition of keywords is implementation-defined or illegal.
#define int int const
#define ptr * const
int i(0);
int ptr j(&i);

typedef int const Int;
typedef int const* const Intp;
Int i(0);
Intp j(&i);

template<class T>
struct C { typedef T const type; typedef T const* const ptr; };
C<int>::type i(0);
C<int>::ptr j(&i);
Perfect answered 4/5, 2010 at 5:12 Comment(10)
-1 for Bad Idea.Amourpropre
We are unclear what you are trying to achieve by this. Surely it isn't just trying to avoid typing const so many times. Or to ask another way: Can you tell us what you hope to achieve by having these const types? There may be a better approach to your final aim. .Arquit
@MtnViewMark: I was honestly just curious to find out what means are available for manipulating the type system at compile time. The actual exercise probably doesn't matter in the slightest. I was quite surprised to find @Amourpropre downvoting me.Perfect
Not sure why you're being downvoted, I think this is an interesting academic (if not very practical) idea. One potential route would be to take an open source compiler and modify it to suit. That's probably the best route.Flournoy
I actually like the idea. I am thinking something along, what if C++ assumed all member-functions const, and you used keyword nonconst to tell that these functions actually change the objects state. Perhaps one could have const class that behaved like that. But ofcourse you would have to change the language to do this.Advise
@Amourpropre Since when has the question containing a bad idea been a valid reason to downvote?Leading
@JonPurdy Did you ever pull this off? I would be interested in a modded compiler which worked this way.Leading
@Kazark: No, my fu wasn’t strong enough back then. I’ll look into it again.Perfect
To the list of suboptimal solutions you can add C++11's template<class T> using c = T const; used as c<int> a = 1.; c<int>* b = &a;Herculie
Yes, over the years, I have noticed that an alarmingly large number of otherwise reasonably skilled programmers just don't get the point of const. They don't understand why const should be used pervasively. I am given to understand that the important new programming language Rust makes storage const by default, variable only by special declaration. That is the right thing to do, in my view. For readers who don't understand this, try taking 1000 lines of C++ code and putting const everywhere possible. You will discover that most symbols are naturally const.Viva
F
13

Take an open source C++ compiler and modify it.

I think the main reason for the downvotes is that people think you're trying to modify C++. Tell them instead you're creating a new language called "C-const" as a university project.

Personally I think it's an interesting idea - you can gain all sorts of performance and readability gains from immutable types - just look at most functional languages.

Flournoy answered 4/5, 2010 at 11:29 Comment(2)
+1 This is definitely the best answer so far, but I'm going to hold off on accepting it to give other answers a chance to catch up to the edited question.Perfect
Actually, since const can be removed via const_cast, you cannot gain performance benefits from it (unless your modified language also disables/modifies the const_cast operator)Graf
A
1

Are you trying to tell the compiler, or tell other people reading or using your code? The compiler won't do much anything different just because a user defined type is used const. Really, all it does is change the set of methods (user defined or implicit) that can be used with that object. In turn, that may allow the compiler to infer some optimizations on the run-time representation.

For class/struct types, you can make this clear to both the compiler and users by simply making every member const:

class Point {
    // An immutable Point data object
    public:
        Point(int ix, int iy): x(ix), y(iy) { }
        Point(const Point& p): x(p.x), y(p.y) { }

        Point add(const Point& p) const;
        int taxiDistance() const;
        // etc... all const members

        const int x, y; // const can only be init'd at construction time

     private:
        Point& operator=(const Point& p); // never implemented!
}
Arquit answered 4/5, 2010 at 5:27 Comment(3)
You got it wrong. He wants to stop writing the word "const" in all those places, and yet have C++ act like the word is there. useless exercise, of course. Anyway I think what he wants is impossible.Mckenna
I answered what I think might be what his true aim might be, since simply trying to avoid typing const is inadvisable and only begs the question why? I've left a comment on the OP asking for clarification.Arquit
@Stefan: Yes, that's the point. Of course it's useless. I probably should have made it clear from the start that I understand what I'm doing and that I'm simply curious.Perfect
R
1

Even if you are able to do this (which I suspect you are not), think about other people reading your code. They are not likely to understand that everything is const and as a result are not likely to understand your code.

Ruffner answered 4/5, 2010 at 5:36 Comment(4)
This is a very negative attitude. Research in programming languages is an entirely valid field of study. If you want to make an incremental change to an existing language, you have to do something non-standard. If everyone took your attitude, no programming language would change ever. An immutable dialect of C++ might be just the right thing for some problems. I suspect not. But I applaud the poster for experimenting and learning.Filefish
Right. The OP's edit wasn't there when I submitted my answer. I didn't realize this question was about learning/ exploring the limits of C++ and/or non-standard extensions / programming techniques. I'm all for experimentation and research, just wanted to emphasize the importance of readable code for the next person to come along. Thanks! -MikeRuffner
Cool! We're all in agreement then.Filefish
@user207442: Note that this answer was made before the question was made clear. It's really appropriately negative in that context. Your points, however, are still quite correct.Perfect
M
0

You could keep the code standard C++ and devise an extra layer of type checking.

An empty MUTABLE macro could serve as an hint for the const checker. Explicit const may still be needed at places to make the code compile.

Menhaden answered 8/10, 2014 at 5:36 Comment(0)
H
-1

I would advice against this. If you manage to achieve you goal anyone (including you after some time) is surprised when he reads your code and it behaves different than he expects.

Please add the const modifier plain visible for everyone wherever it's needed. Your code is going to be read fare more often then it's going to be written!

Hearst answered 4/5, 2010 at 5:36 Comment(1)
Maybe, but lack of const by default is a significant misdesign of C and C++ as programming languages. It would be better, it would be much better, if const were the default and you had to explicitly say var or the like to get a variable. Actually, the need to distinguish constants from variables comes up so often that it's too bad that a punctuation point was not defined for it, like int m (a constant!) and $int m (a variable).Viva

© 2022 - 2024 — McMap. All rights reserved.