Page 1 of 1

Wie erhalte ich ein typisiertes Nullptr-„Literal“?

Posted: 13 Jan 2025, 16:08
by Guest
Ich habe gerade herausgefunden, dass std::is_pointer_v in false übersetzt wird, deshalb der folgende Code:

Code: Select all

template  std::string_view type_str() { /* returns the name of the type */ }
template  const auto type_name = type_str();

template  void fptr(const T *const t) {
if (t)
std::print("{} = {:X}.\n", static_cast(t), *t);
else
std::print("nullptr.\n");
}
// #1
template  requires std::is_pointer_v void f(T t) {
std::print("[{}] is pointer --> ", type_name);
fptr(t);
}
// #2
template  void f(T t) {
std::print("[{}] is NOT pointer.\n", type_name);
}

int main()
{
const auto v0 = 0xfabada;
auto v1 = 0xc0ffee;

f(&v0);
f(&v1);
f(nullptr);

return 0;
}
Erzeugt die folgende Ausgabe:

Code: Select all

[const int*] is pointer --> 0xWHATEVER = FABADA.
[int*] is pointer --> 0xWHATEVER = C0FFEE.
[std::nullptr_t] is NOT pointer.
Ich habe erwartet, dass std::is_pointer_v true ergibt und daher die Funktion Nr. 1 aufgerufen hat, die einzige Problemumgehung Bisher habe ich festgestellt, dass es sich um eine Art typisierten Nullptr handelt:

Code: Select all

template 
constexpr T *NULLPTR = nullptr;

…

f(&v0);
f(&v1);
f(nullptr);
f(NULLPTR);

…
Was druckt:

Code: Select all

[const int*] is pointer --> 0xWHATEVER = FABADA.
[int*] is pointer --> 0xWHATEVER = C0FFEE.
[std::nullptr_t] is NOT pointer.
[int*] is pointer --> nullptr.
Aber ich frage mich, ob es eine andere Möglichkeit gibt, einen Nullptr zu erhalten, der dazu führt, dass std::is_pointer_v wahr ist, ohne eine (Vorlage zu erstellen Variable) Zeigerinstanz, die potenzielle Fehlanwendungen mit sich bringen kann. Das Mitführen der Zeigertypinformationen ist ein Pluspunkt.

Beispielcode hier.