2

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 ::

littlebig
  • 23
  • 4
  • Using enums to define values inside your structs is old and obsolete. You can use `static constexpr` variables instead. – super Mar 13 '21 at 18:57
  • I'm new to this stuff. Thank you for the input, I'll take that into consideration. – littlebig Mar 13 '21 at 19:04
  • also, just inherit from `std:true_type` and false type. All the cool kids do it. `template struct SameType:std::false_type{};`; instead of `result` it exposes `value`, and instances have a bunch of `constexpr` operations as well. – Yakk - Adam Nevraumont Mar 13 '21 at 19:08
  • Yea I've seen that inheritance pattern when I was watching introductory lectures but it was still new to me, I will incorporate it into my structs. Ty for the suggestion – littlebig Mar 13 '21 at 19:14

1 Answers1

2

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
}
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98