模板化的成员函数和参数转发
templated member function and argument forwarding
我正在我的c++游乐场中玩容器,我遇到了相当技术性的问题。
我正试图实现容器的放置方法。现在,它应该接受一个已经构造好的元素,并将其传递给allocator构造方法。
我最终有三个方法,模板化emplaceA
和一对emplaceB1
, emplaceB2
。一切正常
我的问题是emplaceA
没有明确说明Arg
只能是T
(这就是我想要的)。emplaceB1
和emplaceB2
在两个不同的地方提供了几乎相同的实现(我认为这是一个缺陷)。
有解决方法吗?
template<class T, class A> class container {
public:
using allocator_traits = typename std::allocator_traits<A>;
...
template<class Arg> void emplaceA (int n, Arg&& arg){
allocator_traits::construct(allocator_, data_+n, std::forward<Arg>(arg));};
void emplaceB1(int n, const T& t){
allocator_traits::construct(allocator_, data_+n, t);};
void emplaceB2(int n, T&& t){
allocator_traits::construct(allocator_, data_+n, std::move(t));};
...
};
要限制模板化函数,可以使用sfinae来防止发送不需要的类型。
在下面的例子中,我们限制你的模板函数只有在Arg
可转换为T
时才可调用。注意,即使两种类型相同,is_convertible
也可以工作。
template<class Arg, std::enable_if_t<std::is_convertible<Arg, T>::value, int> = 0>
void emplaceA(int n, Arg&& arg){
// ...
}
不要忘记包含标题<type_traits>
当然,如果你想检查发送的类型是否严格是T
,你可能想使用std::is_same
和衰减类型。
template<class Arg, std::enable_if_t<std::is_same<std::decay_t<Arg>, T>::value, int> = 0>
void emplaceA(int n, Arg&& arg){
// ...
}
相关文章:
- 是否可以在不扣除的情况下将模板参数转发到 make_*?
- 可变参数模板参数转发使用逗号运算符
- 如何通过可变参数模板将多个构造函数参数转发到数组初始值设定项列表?
- 将可变参数函数参数转发到 std::function 对象
- 我如何实现变异模式以将可变数量的参数转发到C 11中的函数
- 无临时实例的参数转发
- 如何将构造函数参数转发到 boost::optional
- 如何使包装类将其构造函数参数转发到 std::vector 的构造函数?
- 如何将 CMake 参数转发到外部项目
- 使用std::forward而不是将参数转发到另一个函数
- 使用declard和参数转发构造函数隐式复制结构
- 将可变参数模板参数转发到多个类成员
- Template()的参数转发使构造函数参数变为常量
- 我怎样才能完美地将参数转发到 STL 集合
- 如何在 C++11 中使用可变参数模板正确创建显式参数转发函数
- 使用默认参数转发引用
- 将可变模板参数转发到类似printf的函数
- static_cast的参数转发
- Boost.Program_options:将"--"后面的参数转发到另一个程序
- 将参数转发给模板成员函数