我想编写一个模板来确定类型是否是编译时的stl容器.
我有以下一点代码:
struct is_cont{};
struct not_cont{};
template <typename T>
struct is_cont { typedef not_cont result_t; };
Run Code Online (Sandbox Code Playgroud)
但我不确定如何创建必要的专业化std::vector<T,Alloc>, deque<T,Alloc>, set<T,Alloc,Comp>等...
我编写了类似于类的特性,如果给定类型是"可迭代的",可以使用它来测试.这对于数组(for T[N],not for T[])以及具有a begin和end返回看起来像迭代器的方法的类都是如此.我想知道它是否可以比我更简洁/更简单地完成?
特别是impl命名空间中的东西看起来有点迂回/ hacky.这一切对我来说都有点难看.有关使用此示例并且可以使用g ++和clang ++编译的示例,请参阅:https://gist.github.com/panzi/869728c9879dcd4fffa8
template<typename T>
struct is_iterator {
private:
template<typename I> static constexpr auto test(void*)
-> decltype(
*std::declval<const I>(),
std::declval<const I>() == std::declval<const I>(),
std::declval<const I>() != std::declval<const I>(),
++ (*std::declval<I*>()),
(*std::declval<I*>()) ++,
std::true_type()) { return std::true_type(); }
template<typename I> static constexpr std::false_type test(...) { return std::false_type(); }
public:
static constexpr const bool value = std::is_same<decltype(test<T>(0)), std::true_type>::value;
};
namespace impl {
// implementation details …Run Code Online (Sandbox Code Playgroud) 下面的代码尝试(不使用 c++11)创建一个特征来识别一个类型是否以 STL 方式可迭代:
#include <iostream>
#include <vector>
template<typename C>
struct IsIterable
{
typedef char true_type;
typedef long false_type;
template<class T> static true_type is_beg_iterable(
typename T::const_iterator = C().begin());
template<class T> static false_type is_beg_iterable(...);
enum { value = sizeof(is_beg_iterable<C>()) == sizeof(true_type) };
};
int main() {
std::cout << IsIterable<std::vector<int>>::value << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
还有一个is_end_iterable方法,为简洁起见在此省略
该代码因gcc 4.9.2 *(以及旧版本)和 clang 而失败,并在 VS2012 中成功。我的断言是可变参数版本在重载解析中总是排在最后(因此应该没有歧义),那么谁在这里?
是否有跨平台的解决方法/替代方案?
我现在看到较新版本的 VS 也拒绝代码,所以最后一个问题变得更重要了
我一直在想给我的问题取什么标题,但还是失败了,所以如果你找到一个好的,请编辑它。
我正在尝试为 avector或 other编写一个打印函数,container<T>并为 编写另一个打印函数container<container<T>>,所以这里我想出了:
template<typename T>
void print(T const& cont){
for (const auto& i : cont) {
cout << i << " ";
}
cout << endl;
}
template<typename T, template<typename> typename Cont>
void print(Cont<T> const& cont) {
for (const auto& i : cont) {
print(i);
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里有我的 2 个目标容器:
vector<vector<int>> subsets;
vector<int> subset;
Run Code Online (Sandbox Code Playgroud)
当我调用print(subset);程序时按预期工作,但是当我调用时print(subsets),编译器开始抱怨:
error C2679: binary '<<': no operator found which takes a right-hand operand of …Run Code Online (Sandbox Code Playgroud) 我有一个接收模板参数的函数。
template<class Container>
void function(const Container& object)
{
//here i want to iterate through object and print them
}
int main()
{
function(std::vector<int>{1,3,6,7});
function(std::vector<std::vector<int>>{{1,2,3},{2,5,7}});
}
Run Code Online (Sandbox Code Playgroud)
是否可以在一个函数中执行此操作?假设容器参数是整数。
c++ ×5
templates ×4
stl ×2
c++11 ×1
c++14 ×1
clang ×1
gcc ×1
overloading ×1
traits ×1
type-traits ×1