我有以下代码实现以下类型特征:
- 那种类型是
std::vector
- 该类型是
std::vector
整数
它有效,但非常冗长。
有没有更短/更好的方法来使用概念来编写这个?
我知道我可以从 range-v3 或其他类似库中窃取概念,但假设我想自己实现它。
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>
template <class T>
struct is_vector {
static constexpr bool value = false;
};
template <class T, class A>
struct is_vector<std::vector<T, A> > {
static constexpr bool value = true;
};
template <class T>
struct is_vector_of_int {
static constexpr bool value = false;
};
template <class A>
struct is_vector_of_int<std::vector<int, A> > {
static constexpr bool value = true;
};
// TODO add _v bool
template<typename T>
concept bool Vec = is_vector<T>::value;
template<typename T>
concept bool VecInt = is_vector_of_int<T>::value;
struct my_allocator : public std::allocator<int>{
};
template<VecInt V>
size_t func (const V& v){
return v.size();
}
int main()
{
static_assert(!is_vector<std::string>::value);
static_assert(is_vector<std::vector<int, my_allocator>>::value);
static_assert(is_vector<std::vector<int, std::allocator<int>>>::value);
static_assert(!is_vector_of_int<std::string>::value);
static_assert(is_vector_of_int<std::vector<int, my_allocator>>::value);
static_assert(!is_vector_of_int<std::vector<float, my_allocator>>::value);
static_assert(Vec<std::vector<float, my_allocator>>);
static_assert(!VecInt<std::vector<float, my_allocator>>);
static_assert(Vec<std::vector<int>>);
std::vector<float> vf{1.1,2.2,3.3};
std::vector<int> vi{1,2,3};
// std::cout << func (vf);
std::cout << func (vi);
}