Jen*_*ner 2 c++ templates sfinae c++11 c++17
我试图写一个模板getter函数,该节选std::array<T>
也std::vector<T>
有类型的任意内容T
并返回它的一个值
#include <vector>
#include <array>
class Map2d {
private:
unsigned int m_width;
unsigned int m_height;
unsigned int m_size;
public:
Map2d(unsigned int width, unsigned int height)
: m_width(width), m_height(height) {
m_size = m_width * m_height;
}
template <typename T>
struct is_array_or_vector {
enum { value = false };
};
template <typename T, typename A>
struct is_array_or_vector<std::vector<T, A>> {
enum { value = true };
};
template <typename T, std::size_t N>
struct is_array_or_vector<std::array<T, N>> {
enum { value = true };
};
template <typename V, template <typename, typename...> class T, typename... Args>
typename std::enable_if<is_array_or_vector<T<V, Args...>>::value, V>::type
get(const T<V, Args...>& con, const unsigned int x, const unsigned int y) {
assert(con.size() <= m_size);
return con[m_width * y + x];
}
};
Run Code Online (Sandbox Code Playgroud)
#include "Map2d.h"
int main() {
Map2d map(10, 10);
std::vector<int> v(100);
std::cout << map.get(v, 5, 5) << std::endl; // works
std::array<int, 100> a;
std::cout << map.get(a, 5, 5) << std::endl; // not working
std::list<int> l(100);
std::cout << map.get(l, 5, 5) << std::endl; // should not work
return 1;
}
Run Code Online (Sandbox Code Playgroud)
我需要改变什么才能使其正常工作?我的版本与此答案相比较,区别在于返回值无效且不灵活.
我很感激每一个提示!:)
template <typename T>
typename std::enable_if<is_array_or_vector<T>::value, typename T::value_type>::type
get(const T& con, const unsigned int x, const unsigned int y) {
assert(con.size() <= m_size);
return con[m_width * y + x];
}
Run Code Online (Sandbox Code Playgroud)