If I want to define what is a double -> double function pointer I use:

typedef double (*double_fp1)(double);

But what if I would like to distinguish
const double -> double
it is possible?
And the above definition consists the const double -> duble function?

Dani AI

Generated

Short answer: you cannot distinguish a by-value double parameter from a const double parameter in a function type. A const on a parameter that is passed by value is a top-level qualifier and is ignored when the function type is formed, so the typedef you used will match both forms. To get distinct signatures use pointer or reference types (for example, const double& or const double*), or change the parameter type itself.

was right to suggest trying a compiler — that quickly shows the behavior. 's reply was pointing at making the pointer itself const; that is a different thing: const on the pointer means the pointer cannot be reseated, not that the function parameter is const.

Examples (demonstrating distinct function-pointer types you can actually differentiate):

using FnConstRef = double (*)(const double&);
double byConstRef(const double& x) { return x * x; }
FnConstRef p1 = byConstRef; // distinct type: takes a const reference

using FnConstPtr = double (*)(const double*);
double byConstPtr(const double* x) { return (*x) * (*x); }
FnConstPtr p2 = byConstPtr; // distinct type: takes a pointer-to-const

Quick compile-time check (C++11+):

#include <type_traits>

double f1(double);
double f2(const double);

static_assert(std::is_same<decltype(f1), decltype(f2)>::value, "same type");

Notes and gotchas: const on a return value is also a top-level qualifier and generally ignored in type matching; const on member functions (the foo() const qualifier) is part of the function type for overload resolution; and for small built-ins like double, prefer passing by value unless you need reference semantics or to express immutability to the caller (then use const& or const*).

Recommended Answers

All 2 Replies

>it is possible?
Have you tried it? A lot of your questions can be tested with a compiler and a small bit of code.

If I want to define what is a double -> double function pointer I use:

typedef double (*double_fp1)(double);

But what if I would like to distinguish
const double -> double
it is possible?
And the above definition consists the const double -> duble function?

you mean :

const double_fp1  =  &myDoubleFunction;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.