cib*_*en1 22 c++ templates c++11
假设我们有这个 template
template<typename Container, typename T>
bool contains (const Container & theContainer, const T & theReference) {
...
}
Run Code Online (Sandbox Code Playgroud)
如何说明,容器中的元素显然应该是类型T
?
这一切都可以缩写(也许在C++ 11中)?
qua*_*dev 27
虽然使用的其他答案value_type
都是正确的,但这个常见问题的规范解决方案是首先不传递容器:使用标准库语义,并传递一对迭代器.
通过传递迭代器,您不必担心容器本身.你的代码也更通用:你可以对范围采取行动,你可以使用反向迭代器,你可以将你的模板与其他标准算法等结合起来.:
template<typename Iterator, typename T>
bool contains (Iterator begin, Iterator end, const T& value) {
...
}
int main(){
std::vector<int> v { 41, 42 };
contains(std::begin(v), std::end(v), 42);
};
Run Code Online (Sandbox Code Playgroud)
如果要检查所携带的类型Iterator
,可以使用std::iterator_traits
:
static_assert(std::is_same<typename std::iterator_traits<Iterator>::value_type, T>::value, "Wrong Type");
Run Code Online (Sandbox Code Playgroud)
(请注意,通常不需要此断言:如果提供的值与之不相符T
,则模板将不会首先编译)
最终的模板看起来像:
template<typename Iterator, typename T>
bool contains (Iterator begin, Iterator end, const T& value) {
static_assert(std::is_same<typename std::iterator_traits<Iterator>::value_type, T>::value, "Wrong Type");
while(begin != end)
if(*begin++ == value)
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
笔记:
1)这不应该是一个惊喜,但我们的contains
模板现在具有几乎相同的签名std::find
(返回迭代器):
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );
Run Code Online (Sandbox Code Playgroud)
2)如果修改原始签名contains
太多,您可以随时将呼叫转发到我们的新模板:
template<typename Container, typename T>
bool contains (const Container & theContainer, const T & theReference) {
return contains(std::begin(theContainer), std::end(theContainer), theReference);
}
Run Code Online (Sandbox Code Playgroud)
小智 21
您可以限制模板中的容器类型:
#include <algorithm>
#include <iostream>
#include <vector>
template< template<typename ... > class Container, typename T>
bool contains(const Container<T>& container, const T& value) {
return std::find(container.begin(), container.end(), value) != container.end();
}
int main()
{
std::vector<int> v = { 1, 2, 3 };
std::cout << std::boolalpha
<< contains(v, 0) << '\n'
<< contains(v, 1) << '\n';
// error: no matching function for call to ‘contains(std::vector<int>&, char)’
contains(v, '0') ;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
一个更完整的解决方案(解决一些评论):
#include <algorithm>
#include <array>
#include <iostream>
#include <map>
#include <set>
#include <vector>
// has_member
// ==========
namespace Detail {
template <typename Test>
struct has_member
{
template<typename Class>
static typename Test::template result<Class>
test(int);
template<typename Class>
static std::false_type
test(...);
};
}
template <typename Test, typename Class>
using has_member = decltype(Detail::has_member<Test>::template test<Class>(0));
// has_find
// ========
namespace Detail
{
template <typename ...Args>
struct has_find
{
template<
typename Class,
typename R = decltype(std::declval<Class>().find(std::declval<Args>()... ))>
struct result
: std::true_type
{
typedef R type;
};
};
}
template <typename Class, typename ...Args>
using has_find = has_member<Detail::has_find<Args...>, Class>;
// contains
// ========
namespace Detail
{
template<template<typename ...> class Container, typename Key, typename ... Args>
bool contains(std::false_type, const Container<Key, Args...>& container, const Key& value) {
bool result = std::find(container.begin(), container.end(), value) != container.end();
std::cout << "Algorithm: " << result << '\n';;
return result;
}
template<template<typename ...> class Container, typename Key, typename ... Args>
bool contains(std::true_type, const Container<Key, Args...>& container, const Key& value) {
bool result = container.find(value) != container.end();
std::cout << " Member: " << result << '\n';
return result;
}
}
template<template<typename ...> class Container, typename Key, typename ... Args>
bool contains(const Container<Key, Args...>& container, const Key& value) {
return Detail::contains(has_find<Container<Key, Args...>, Key>(), container, value);
}
template<typename T, std::size_t N>
bool contains(const std::array<T, N>& array, const T& value) {
bool result = std::find(array.begin(), array.end(), value) != array.end();
std::cout << " Array: " << result << '\n';;
return result;
}
// test
// ====
int main()
{
std::cout << std::boolalpha;
std::array<int, 3> a = { 1, 2, 3 };
contains(a, 0);
contains(a, 1);
std::vector<int> v = { 1, 2, 3 };
contains(v, 0);
contains(v, 1);
std::set<int> s = { 1, 2, 3 };
contains(s, 0);
contains(s, 1);
std::map<int, int> m = { { 1, 1}, { 2, 2}, { 3, 3} };
contains(m, 0);
contains(m, 1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Jar*_*d42 19
对于标准容器,您可以使用value_type
:
template<typename Container>
bool contains (const Container & theContainer, const typename Container::value_type& theReference) {
...
}
Run Code Online (Sandbox Code Playgroud)
请注意,const_reference
在您的情况下也有:
template<typename Container>
bool contains (const Container & theContainer, typename Container::const_reference theReference) {
...
}
Run Code Online (Sandbox Code Playgroud)
您可以检查value_type
容器和T
使用static_assert
template<typename Container, typename T>
bool contains (const Container & theContainer, const T & theReference) {
static_assert( std::is_same<typename Container::value_type, T>::value,
"Invalid container or type" );
// ...
}
Run Code Online (Sandbox Code Playgroud)
演示 Here
使用std::enable_if
(http://en.cppreference.com/w/cpp/types/enable_if),但有点复杂static_assert
.
编辑:根据P0W的评论,使用std::enable_if
允许我们使用SFINAE,当你决定有更多的重载时这是很好的.例如,如果编译器决定使用这个模板化函数,并且Container
没有value_type
typedefed,它就不会立即生成错误,就像static_assert
会查找完全符合签名的其他函数一样.
在Visual Studio 12上测试过.
#include <vector>
#include <iostream>
template<typename Container, typename T>
typename std::enable_if<
std::is_same<T, typename Container::value_type>::value, bool>::type //returns bool
contains(const Container & theContainer, const T & theReference)
{
return (std::find(theContainer.begin(), theContainer.end(), theReference) != theContainer.end());
};
int main()
{
std::vector<int> vec1 { 1, 3 };
int i = 1;
float f = 1.0f;
std::cout << contains(vec1, i) << "\n";
//std::cout << contains(vec1, f); //error
i = 2;
std::cout << contains(vec1, i) << "\n";
};
Run Code Online (Sandbox Code Playgroud)
输出:
1
0
Run Code Online (Sandbox Code Playgroud)
PS:你的原始函数也是这样做的,除了允许派生类.这些解决方案没有.
归档时间: |
|
查看次数: |
2673 次 |
最近记录: |