如何使用模板结构而不是函数检查容器类型?

编程入门 行业动态 更新时间:2024-10-24 11:20:22
本文介绍了如何使用模板结构而不是函数检查容器类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在这篇文章中 检查 stl 容器中元素的类型 - c++ 用户 UncleBens 展示了如何使用结构体 same_type 和函数 containers_of_same_type

In this post check type of element in stl container - c++ user UncleBens showed how to check the type of a container using a struct same_type and a function containers_of_same_type

我正在尝试做同样的事情,除了我想使用结构而不是使用函数来检查容器.我有以下代码,但它给了我错误:

Im trying to do the same thing, except, instead of using a function for checking the containers, I want to use a struct. I have the following code, but it is giving me errors:

// Working
template<typename X, typename Y>
struct SameType {
    enum { result = 0 };
};

// Working
template<typename T>
struct SameType<T, T> {
    enum { result = 1 };
};

// This struct is not working
template<typename C1, typename C2>
struct SameContainerType {
    enum { value = SameType<typename C1::value_type, typename C2::value_type>::result };
};

#include <iostream>
#include <vector>
#include <list>

int main() {
    std::cout << SameType<int, int>::result << std::endl;;     // 1
    std::cout << SameType<int, double>::result << std::endl;;  // 0
    std::cout << SameContainerType<std::vector<int>(), std::list<int>()>::value;  // error
}

错误是,C1C2 必须是命名空间或类才能使用 ::

The error is, C1 and C2 must be a namespace or class to use ::

推荐答案

std::vector() 是一个返回 std::vector.您需要删除 ().

std::vector<int>() is a function which returns a std::vector<int>. You need to remove the ().

int main() {
    std::cout << SameType<int, int>::result << std::endl;;     // 1
    std::cout << SameType<int, double>::result << std::endl;;  // 0
    std::cout << SameContainerType<std::vector<int>, std::list<int>>::value; // 1
}

这篇关于如何使用模板结构而不是函数检查容器类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 06:40:57,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   容器   函数   而不是   模板

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!