【发布时间】:2017-06-23 11:26:59
【问题描述】:
我正在尝试编写一个模板化的 getter 函数,它除了 std::array<T> 和 std::vector<T> 之外的任意内容类型为 T 并返回它的一个值
Map2d.h
#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];
}
};
Main.cpp
#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;
}
我需要进行哪些更改才能使其正常工作?我的版本可以与answer 相比,不同之处在于返回值是无效的并且不灵活。
感谢您的每一个提示! :)
【问题讨论】:
-
你应该从
::std::integral_constant< bool, false >而不是enum { value = false };派生is_array_or_vector。 -
你能指出我更多正确的方向吗?不幸的是,我对你的小费无能为力:((
-
@JensMetzner:你考虑过使用the GSL type
span吗?毕竟,您为什么要禁止获取任何代表Ts 连续范围的对象?
标签: c++ c++11 templates sfinae c++17