简体   繁体   English

模板参数的模板化模板专业化

[英]Templated template specialization for template argument

Say you have the following: 说您有以下几点:

SomeType *x;
std::vector<std::unique_ptr<SomeType>> v;

And you want to call a function like this: 您想调用一个这样的函数:

do_something(v.begin(), v.end(), x);

Say do_something is templated, and you want to make a specialization for the case of container<unique_ptr<T>> . 假设do_something是模板化的,并且您想对container<unique_ptr<T>>的情况进行专门化。 Even if not for specialization, let's simply say we want to have the container templatized but always assuming inside it is a unique_ptr . 即使不进行专业化,也可以简单地说我们要对container模板化,但始终假设其内部是unique_ptr

I tried the following: 我尝试了以下方法:

template<template <typename X, typename Y> class C, typename T, typename Allocator>
inline int do_something(typename C<std::unique_ptr<T>, Allocator>::iterator first,
                        typename C<std::unique_ptr<T>, Allocator>::iterator last,
                        const T* value)
{ ... }

But g++, clang and cl.exe all fail to deduce the type of C . 但是g ++,clang和cl.exe都无法推断C的类型。 What's ambiguous here? 这里有什么歧义? And what can I do about it? 那我该怎么办?

Anything to the left of :: is a non-deduced context. ::左侧的任何内容都是不可推论的上下文。

Here's something that will allow your function to be called on any iterator whose value_type is a std::unique_ptr . 这是允许在value_typestd::unique_ptr任何迭代器上调用函数的方法。

#include <type_traits>

template <typename T>
struct is_unique_ptr : public std::false_type {};
template <typename T, typename D>
struct is_unique_ptr<std::unique_ptr<T,D>> : public std::true_type {};

template <typename Iter, typename T>
auto do_something(Iter first, Iter last, const T* value) ->
std::enable_if_t<is_unique_ptr<typename std::iterator_traits<Iter>::value_type>
                 ::value, int>
{ ... }

Note this now includes not just Container::iterator but Container::reverse_iterator and any other "wrapper" iterator with the same value_type . 请注意,这不仅包括Container::iterator而且还包括Container::reverse_iterator和其他具有相同value_type “包装”迭代器。 (But not Container::const_iterator .) (但不是Container::const_iterator 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM