How can I check that function really get a variable that defined as const?


How can I check that function really get a variable that defined as const?



Given the following code:


template <class Func>
void f(Func func , int* param){
func(/* how can I send "param" as const "int*" */);
}



How can I do it so that if f don't get the variable as const - so we will get error ?


f





Some minimal code would be handy for an answer to fill in the blank.
– chris
Jun 29 at 9:10





@chris I edited my question (and I added example in order to clarify my question).
– Software_t
Jun 29 at 9:17





Which one do you want? "Const pointer" or "pointer to const"?
– Nicky C
Jun 29 at 9:19




1 Answer
1



If you want to make sure that f accepts a pointer to const-qualified int you can cast function argument appropriately:


f


f(static_cast<int const *>(param));



Alternatively, if you want to make sure that f accepts a reference to const-qualified pointer you can add const qualifier to function argument:


f


void f(Func f , int * const param)





I thought about it too, but it's not doing the opposite thing? Namely, static_cast don't remove the "const" from param?
– Software_t
Jun 29 at 9:19


static_cast





@Software_t It is const_cast that removes const
– VTT
Jun 29 at 9:20



const_cast


const





I am sorry, you right. Can you explain if I can do it with dynamic_cast in this case or not (and why) ?
– Software_t
Jun 29 at 9:27


dynamic_cast





@Software_t: Sure, that would degenerate to a static_cast there. Imho, they should have added no_cast when they added all the explicit casts, which is enough here.
– Deduplicator
Jun 29 at 9:30


static_cast


no_cast






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV