如何从成员函数返回任何int整型容器?在下面的代码我试过两个测试类,但没有之间maany排列似乎用G ++编译 - 4.8.2:模板模板从成员函数返回类型
#include "vector"
struct test {
template<class Container> Container<int> ret() {
return Container<int>();
}
};
struct test {
template<
template<class Int> class Container,
class Int
> typename Container<Int> ret() {
return Container<Int>();
}
};
int main() {
std::vector<int> v = test().ret<std::vector<int> >();
return 0;
}
理想情况下,程序会C++ 03只编译如果INT是包含类型。在其他情况下向用户打印可读的错误也会很好,但我想这需要boost或std static_assert()。谢谢!
编辑1
不幸的是,2模板参数的版本只适用于少数性病容器,注释掉那些引起编译错误,因为它们需要不同的模板参数:
struct test {
template<
template<class, class> class Container
> Container<int, std::allocator<int> > ret() {
return Container<int, std::allocator<int> >();
}
};
int main() {
std::vector<int> v = test().ret<std::vector>();
std::list<int> l = test().ret<std::list>();
//std::set<int> se = test().ret<std::set>();
std::deque<int> d = test().ret<std::deque>();
//std::stack<int> st = test().ret<std::stack>();
//std::queue<int> q = test().ret<std::queue>();
//std::priority_queue<int> p = test().ret<std::priority_queue>();
return 0;
}
但以下C++ 11版似乎适用于每个容器:
struct test {
template<
template<class, class...> class Container,
class... Container_Params
> Container<int, Container_Params... > ret() {
return Container<int, Container_Params... >();
}
};
int main() {
auto v = test().ret<std::vector>();
auto l = test().ret<std::list>();
auto se = test().ret<std::set>();
auto d = test().ret<std::deque>();
auto st = test().ret<std::stack>();
auto q = test().ret<std::queue>();
auto p = test().ret<std::priority_queue>();
auto us = test().ret<boost::unordered_set>();
return 0;
}
'std :: vector' is no一种类型 – tumdum