She*_*ohn 8 c++ templates iterator const
我有两个半密切相关的问题.给定作为模板参数传递的STL迭代器类型:
enable_if除了1.,如何强制(例如使用s)此类型对应于非const迭代器?这个问题来自哪里:
我写了一个小类来促进对向量的算术/关系/代数运算(通过向量我的意思是1d固定大小的数据,而不是STL向量).我没有强制使用特定的数据容器,而是定义了一个接口并派生了几个可能的容器,它们基本上"包装"了各种存储数据的方式.其中一个容器是STL迭代器的包装器,我遇到了一些麻烦.
问题1:
您可以使用以下类型特征:
template<typename T, typename = void>
struct is_const_iterator : std::false_type { };
template<typename T>
struct is_const_iterator<T,
typename std::enable_if<
std::is_const<
typename std::remove_pointer<
typename std::iterator_traits<T>::pointer
>::type
>::value
>::type> : std::true_type { };
Run Code Online (Sandbox Code Playgroud)
这是一个演示:
#include <type_traits>
#include <iterator>
#include <list>
#include <vector>
template<typename T, typename = void>
struct is_const_iterator : std::false_type { };
template<typename T>
struct is_const_iterator<T,
typename std::enable_if<
std::is_const<
typename std::remove_pointer<
typename std::iterator_traits<T>::pointer
>::type
>::value
>::type> : std::true_type { };
int main()
{
typedef std::list<int>::iterator LI;
typedef std::list<int>::const_iterator CLI;
static_assert(is_const_iterator<LI>::value, "!"); // Fires
static_assert(is_const_iterator<CLI>::value, "!"); // Does not fire
typedef std::vector<int>::iterator VI;
typedef std::vector<int>::const_iterator CVI;
static_assert(is_const_iterator<VI>::value, "!"); // Fires
static_assert(is_const_iterator<CVI>::value, "!"); // Does not fire
}
Run Code Online (Sandbox Code Playgroud)
这是一个实例.
问题2:
使用上述类型特征,这变得简单.假设您有一个foo()要约束的函数模板,以便它只接受非const迭代器:
template<typename It,
typename std::enable_if<!is_const_iterator<It>::value>::type* = nullptr>
void foo(It i)
{
// Does something with i...
}
Run Code Online (Sandbox Code Playgroud)
还有一个简单的演示程序:
int main()
{
std::vector<int> v;
foo(v.begin()); // OK
foo(v.cbegin()); // ERROR!
}
Run Code Online (Sandbox Code Playgroud)
这是一个实例.
| 归档时间: |
|
| 查看次数: |
250 次 |
| 最近记录: |