如何检查模板对是否有价值

How to check if a template pair has value

我正在使用模板片段在 C++ 中编写一个 trie 结构:

pair<char,T>

我有一个方法 void empty() ,我想在其中检查根的 第二个值 是否未设置(值等于默认构造函数值或详细信息:值将存储其他对类型。)。我知道默认构造函数会将 0 应用于数据类型 int,但我如何在模板中检查它?

另一个 post 提到了这个: return root == new Trie() (因未知 == 运算符而失败)

提前致谢

std::pairs 成员不能“未设置”。

您可以使用 std::optional 为可选值建模。


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

当然你可以检查当前值是否等于初始值:

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>";
}

或者对于 std::pair<int,T> 的第二个成员:

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

完整示例:

#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);
}