Proposal for explict keyword for non constructor functions

So we have the explicit specifier for constructors, would it be better if we could have explicit for any type of callable functions as well. At the moment we can use a template function where the template parameters are set to a specific type:

1
2
3
4
template <typename T = double>
T f(T) {
// ...
}


I would also like to avoid using RTTI for this purpose.

So I think it would be better to have the syntatic sugar, this usage meaning that all the parameters have to be explicit:

1
2
3
explicit void f(double input) {
// ...
}


Going further, we could have the explicit being optional for some of the function parameters:

1
2
3
void f(explicit double input, float other) {
// ...
}


While we are at it, I propose to have a way of turning off implicit type conversion, maybe with a #pragma and/or a compiler option? The #pragma would be for Translation Unit level control, while the compiler option would be global. Implicit type conversions are the source of many errors according to Jason Turner.

Any thoughts?
Last edited on
Can you explain the difference in behavior on the calling side?

Edit: Ah, you mean, if foo was explicit, this would not compile:
1
2
3
4
5
void foo(double bar) { }

int main() {    
    foo((char)42);
}


Seems like a good proposal to me, but if you're serious about trying to get a new proposal into the language,
you should look at https://isocpp.org/std/submit-a-proposal
Last edited on
@Ganado

Cheers, I am aware of the iso cpp site, I wanted to see what people thought, just in case someone had a better idea.

I have seen the documentation about user conversion functions, but it would seem a pain to have to create those, and they are for class types, I would like them for any callable.


https://en.cppreference.com/w/cpp/language/cast_operator.html
IMO anything which can detect 'issues' at compile time is to welcomed.
Cheers seeplus

Also kind of related to this is the idea of list initialising function arguments with braces to warn if there is narrowing:

1
2
3
4
5
6
7
8
9
int foo(int input) {return input;}

int main() {

double a{2.0};

int b = foo({a}); // error narrowing of type

}


But this is a bit limiting, I would like something more greedy.
Registered users can post here. Sign in or register to post.