Warm tip: This article is reproduced from serverfault.com, please click

How to check if a template pair has value

发布于 2020-11-30 17:59:44

i'm coding a trie structure in C++ with a template snippet:

pair<char,T>

I have a method void empty() in which I want to check, whether the root's second value is not set (value is equal to default constructor value or in detail: values would store other pair types.). I know that the default constructor would apply 0 for the data type int, but how can i check this inside the template ?

Another post mentioned this: return root == new Trie<char,T>() (failed duo to unknown == operator)

Thanks in advance

Questioner
Danzon2504
Viewed
0
largest_prime_is_463035818 2020-12-01 02:18:06

A std::pairs member cannot be "not set".

You can use std::optional to model an optional value.


"...value is equal to default constructor..."

Of course you can check if the current value equals the initial one:

std::pair<int,int> x;
if (x.first == 0) {
    std::cout << "value of x.first is that of a default constructed std::pair<int,int>";
}

Or for the second member of a std::pair<int,T>:

if (x.second == T{} ) {
    std::cout << "second has same value as a default constructed T";
}

Complete example:

#include <iostream>
#include <utility>

template <typename T>
bool check_if_default_second(const std::pair<int,T>& p) {
    return p.second == T{};
}


int main() {
    std::pair<int,int> p;
    std::cout << check_if_default_second(p);
}