如何使用模板结构而不是函数检查容器类型? [英] How to check type of container using template struct instead of function?

查看:27
本文介绍了如何使用模板结构而不是函数检查容器类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这篇文章中 检查 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆