Search code examples
c++constexprdecltype

Why does my isVector function not return true?


Based on this question, I experimented with a is_vector trait:

#include <iostream>
#include <vector>

using namespace std;

template<typename T>
struct is_vector { 
        constexpr static bool value = false;
};

template<typename T>
struct is_vector<std::vector<T>> { 
        constexpr static bool value = true;
};

int main() { 
    int A;
    vector<int> B;

    cout << "A: " << is_vector<decltype(A)>::value << endl;
    cout << "B: " << is_vector<decltype(B)>::value << endl;

    return 0;
}

Output:

A: 0
B: 1

This works as expected. However, when I try to put this in a small helper function, is_vector returns false for B:

template<typename T>
constexpr bool isVector(const T& t) { 
        return is_vector<decltype(t)>::value;
}
...
cout << "B: " << isVector(B) << endl;  // Expected ouptput: "B: 1"

Output:

B: 0

What am I missing here?


Solution

  • The issue here is t is a const std::vector<int>& which does not match struct is_vector<std::vector<T>>. What you really want in your function is to use T which is deduced as std::vector<T> which does work. Doing that you get

    template<typename T>
    constexpr bool isVector(const T& t) { 
            return is_vector<T>::value;
    }