【发布时间】:2016-04-29 14:50:13
【问题描述】:
出于我希望能够做到这一点的原因;
vector<int> p = {1, 2};
vector<vector<int>> q = {p, {0, 1}};
auto t = test(p);
auto u = test(q); // Fails with below implementation
特别是 test 被模板化以接受自定义类,这些类可能会或可能不会针对一或两个(目前)维度进行迭代。我试图通过检查给定的内容是否具有size 函数来确定要做什么;
template<typename T> struct hasSize {
template<typename U, size_t(U::*)() const> struct SFINAE {};
template<typename U> static char Test(SFINAE<U, &U::size>*);
template<typename U> static int Test(...);
static const bool value = sizeof(Test<T>(0)) == sizeof(char);
};
template<typename iterable> int test(const iterable &x, std::false_type) {
return (int) x;
}
template<typename iterable> int test(const iterable &x, std:: true_type) {
int total = 0;
for(auto &each : x)
total += test(each,
std::integral_constant<bool, hasSize<decltype(each)>::value>());
return total;
}
template<typename iterable> int test(const iterable &view) {
return test(view, std::true_type());
}
在放弃this 答案后,我将hasSize 基于here 给出的答案,因为这似乎只适用于成员变量,而不适用于函数。我还尝试了第一次讨论中给出的has_const_reference_op 的修改版本,但这有同样的问题。
给出的错误表明没有第二次应用 SNIFAE;
error C2440: 'type cast':
cannot convert from 'const std::vector<int, std::allocator<_Ty>>' to 'int'
note: No user-defined-conversion operator available that can perform this conversion,
or the operator cannot be called
note: see reference to function template instantiation
'int test<iterable>(const iterable &, std::false_type)' being compiled
with iterable = std::vector<int,std::allocator<int>>
但我不知道为什么。
【问题讨论】:
-
你可能想要
hasSize<typename std::decay<decltype(each)>::type>::value>() -
也许对你来说不是重点,但我认为你需要做的不仅仅是检查
size()函数的存在以确定一个类型是否由嵌套容器组成。例如,字符串类有一个size()函数。
标签: c++ templates visual-studio-2013