Search code examples
c++template-meta-programming

How to check type of container using template struct instead of function?


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
}

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


Solution

  • 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
    }