如何专门化const和非const容器的模板
How to specialize a template for const and non const containers?
我试图使模板的2专业化:
- 接受非const容器
- 另一个接受const容器
我的当前代码是:
template<class T>
struct A{
constexpr static int value=0;
};
template<template<typename>class T,typename...Args>
struct A<T<Args...>>{//accept non const containers
constexpr static int value=1;
};
template<template<typename>class T,typename...Args>
struct A<T<Args...> const>{//accept const containers
constexpr static int value=2;
};
ideone
但是这段代码不起作用,如果我使用const容器,它使用第一个A
的实例化而不是第三个。
using Type=const std::array<int,10>;
std::cout<<A<Type>::value;//output is 0
我试着删除
template<class T>
struct A{
constexpr static int value=0;
};
但是它给出了很多错误…
我认为你可以做到这一点没有可变的模板参数:
template<class T>
struct A{
constexpr static int value=0;
};
template<class T>
struct A<T const> {
constexpr static int value=2;
};
int main()
{
std::cout << A<const std::vector<int>>::value;
}
你希望模板模板形参有可变的模板参数列表(实际上所有标准容器都有多个模板形参):
template< template<typename...> class T, typename...Args >
// ^^^
那么这个代码
#include <vector>
#include <iostream>
template<class T>
struct A{
constexpr static int value=0;
};
template<template<typename...>class T,typename...Args>
struct A<T<Args...>>{//accept non const containers
constexpr static int value=1;
};
template<template<typename...>class T,typename...Args>
struct A<T<Args...> const>{//accept const containers
constexpr static int value=2;
};
int main()
{
std::cout << A<const std::vector<int>>::value;
}
输出2
。
但是它仍然不能与std::array
一起工作,因为它在其参数列表中包含一个非类型模板参数(并且不能匹配可变类型包)。这恐怕不能用一般的方法解决。
始终使用type_traits。http://en.cppreference.com/w/cpp/types/is_const
#include <type_traits>
#include <iostream>
#include <array>
#include <vector>
int main()
{
std::cout << std::is_const< const std::vector<int> > ::value << 'n';
std::cout << std::is_const< std::vector<int> >::value << 'n';
std::cout << std::is_const< const std::array<int, 4> >::value << 'n';
std::cout << std::is_const< std::array<int, 4> > ::value << 'n';
}
输出如预期:
1
0
1
0
相关文章:
- 如何避免将 const 和非 const 成员函数输入到模板中的代码重复
- 如何避免重复的const和非const虚拟函数?是否可以
- 避免使用 auto 关键字从字面上复制 const 和非 const 的代码?
- 为什么在const和非const方法中删除代码重复不是不确定的行为
- 返回一个 const 和非 const 包装器对象
- 在使用指向 const 和非 const 方法的成员指针时减少模板专用化的数量
- 为什么BOOST.RANGE RANGE_BEGIN/END FREE功能对const和非const引用都重载
- Const和非常量函子
- 如何删除抽象类中类似的 const 和非 const 成员函数之间的代码重复
- 同一函数的const和非const版本——反模式
- 避免在const和非const成员函数中重复代码
- c++中返回引用的重载const和非const类方法
- 公开begin()和end()的const和非const版本,以使用智能指针迭代成员向量
- 树的const和非const版本的访问模式
- 应用于const和非const对象的引用返回方法
- 如何专门化const和非const容器的模板
- 定义遍历函数的const和非const版本
- 宏解决方案的重复,const和非const, getter
- Range-v3:使用view_facade来同时提供const和非const迭代器
- 不能使用操作符重载比较const和非const模板类型