c++ 模板类;具有任意容器类型的函数,如何定义它? [英] c++ template class; function with arbitrary container type, how to define it?

查看:33
本文介绍了c++ 模板类;具有任意容器类型的函数,如何定义它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,简单的模板问题.假设我像这样定义我的模板类:

template类 foo {上市:foo(T const& first, T const& second) : first(first), second(second) {}模板void bar(C& 容器,T const& baz){//...}私人的:第一;T秒;}

问题是关于我的 bar 函数...我需要它能够使用某种标准容器,这就是为什么我包含模板/类型名称 C 部分来定义该容器类型.但显然这不是正确的方法,因为我的测试班然后抱怨:

错误:'bar' 未在此范围内声明

那么我将如何以正确的方式实现我的栏功能?也就是说,作为我的模板类的一个函数,具有任意容器类型......我的模板类的其余部分工作正常(具有不会导致错误的其他函数),这只是一个有问题的函数.

好的,所以特定函数(bar)是一个 eraseInRange 函数,它擦除指定范围内的所有元素:

void eraseInRange(C& container, T const& firstElement, T const& secondElement) {...}

一个如何使用它的例子是:

eraseInRange(v, 7, 19);

在这种情况下,v 是一个向量.

编辑 2:傻我!我应该在我的班级之外声明这个函数,而不是在里面……这是一个非常令人沮丧的错误.无论如何,感谢大家的帮助,虽然问题有点不同,但这些信息确实帮助我构建了函数,因为在找到我原来的问题后,我确实遇到了其他一些令人愉快的错误.所以谢谢你!

解决方案


特征解决方案.

概括不要超过需要,不要少于.

在某些情况下,该解决方案可能还不够,因为它会匹配具有此类签名的任何模板(例如 shared_ptr),在这种情况下,您可以使用 type_traits,非常像 duck-typing(模板通常是鸭式的).

#include //Helper 判断是否有一个用于 T 的 const_iterator.模板结构 has_const_iterator{私人的:模板静态字符测试(类型名 C::const_iterator*);模板静态整数测试(...);上市:枚举 { value = sizeof(test(0)) == sizeof(char) };};//bar() 是为也定义了 const_iterator 的容器定义的//作为 value_type.模板 typename std::enable_if::value,无效>::类型bar(const Container &c, typename Container::value_type const & t){//注意:不需要对 value_type 进行额外检查,检查是为了//已经在函数签名中释放了.}模板 类DoesNotHaveConstIterator {};#include <向量>int主(){std::vectorC;酒吧 (c, 1.2f);DoesNotHaveConstIterator乙;酒吧 (b, 1.2f);//正确编译失败}

一个好的模板通常不会人为地限制它们有效的类型(为什么要?).但是想象一下,在上面的示例中,您需要访问对象 const_iterator,然后您可以使用 SFINAE 和 type_traits 将这些约束放在您的函数上.


或者只是像标准库那样

概括不要超过需要,不要少于.

template void bar (Iter it, Iter end) {for (; it!=end; ++it) {/*...*/}}#include <向量>int主(){std::vectorC;酒吧 (c.begin(), c.end());}

有关更多此类示例,请查看 .

这种方法的优势在于其简单性,并且基于ForwardIterator 等概念.它甚至适用于数组.如果你想直接在签名中报告错误,你可以将它与特征结合起来.


std 带有类似 std::vector 签名的容器(不推荐)

Kerrek SB 已经近似了最简单的解决方案,尽管它是无效的 C++.修正后的变体如下:

#include //对于 std::allocator模板<模板<类型名称,类型名称>类容器,类型名称值,typename Allocator=std::allocator>void bar(const Container<Value, Allocator> & c, const Value & t){//}

但是:这仅适用于恰好具有两个模板类型参数的容器,因此对于 std::map 会失败(感谢 Luc Danton).


任何类型的辅助模板参数(不推荐)

任何次要参数计数的修正版本如下:

#include //对于 std::allocator<>模板<模板<类型名称,类型名称...>类容器,类型名称值,类型名称... AddParams >void bar(const Container<Value, AddParams...> & c, const Value & t){//}模板 类 OneParameterVector {};#include <向量>int主(){OneParameterVector乙;酒吧 (b, 1.2f);std::vectorC;酒吧 (c, 1.2f);}

但是:对于非模板容器,这仍然会失败(感谢 Luc Danton).

Okay, simple template question. Say I define my template class something like this:

template<typename T>
class foo {
public:
    foo(T const& first, T const& second) : first(first), second(second) {}

    template<typename C>
    void bar(C& container, T const& baz) {
        //...
    }
private:
    T first;
    T second;
}

The question is about my bar function... I need it to be able to use a standard container of some sort, which is why I included the template/typename C part, to define that container type. But apparently that's not the right way to do it, since my test class then complains that:

error: 'bar' was not declared in this scope

So how would I go about implementing my bar function the proper way? That is, as a function of my template class, with an arbitrary container type... the rest of my template class works fine (has other functions that don't result in an error), it's just that one function that's problematic.

EDIT: Okay, so the specific function (bar) is an eraseInRange function, that erases all elements in a specified range:

void eraseInRange(C& container, T const& firstElement, T const& secondElement) {...}

And an example of how it would be used would be:

eraseInRange(v, 7, 19);

where v is a vector in this case.

EDIT 2: Silly me! I was supposed to declare the function outside of my class, not in it... pretty frustrating mistake to be making. Anyways, thanks everyone for the help, though the problem was a little different, the information did help me construct the function, since after finding my original problem, I did get some other pleasant errors. So thank you!

解决方案


Traits solution.

Generalize not more than needed, and not less.

In some cases that solution might not be enough as it will match any template with such signature (e.g. shared_ptr), in which case you could make use of type_traits, very much like duck-typing (templates are duck typed in general).

#include <type_traits>

// Helper to determine whether there's a const_iterator for T.
template<typename T>
struct has_const_iterator
{
private:
    template<typename C> static char test(typename C::const_iterator*);
    template<typename C> static int  test(...);
public:
    enum { value = sizeof(test<T>(0)) == sizeof(char) };
};


// bar() is defined for Containers that define const_iterator as well
// as value_type.
template <typename Container>
typename std::enable_if<has_const_iterator<Container>::value,
                        void>::type
bar(const Container &c, typename Container::value_type const & t)
{
  // Note: no extra check needed for value_type, the check comes for
  //       free in the function signature already.
}


template <typename T>
class DoesNotHaveConstIterator {};

#include <vector>
int main () {
    std::vector<float> c;
    bar (c, 1.2f);

    DoesNotHaveConstIterator<float> b;
    bar (b, 1.2f); // correctly fails to compile
}

A good template usually does not artificially restrict the kind of types for which they are valid (why should they?). But imagine in the example above you need to have access to an objects const_iterator, then you can use SFINAE and type_traits to put those constraints on your function.


Or just to as the standard library does

Generalize not more than needed, and not less.

template <typename Iter>
void bar (Iter it, Iter end) {
    for (; it!=end; ++it) { /*...*/ }
}

#include <vector>
int main () {
    std::vector<float> c;
    bar (c.begin(), c.end());
}

For more such examples, look into <algorithm>.

This approach's strength is its simplicity and is based on concepts like ForwardIterator. It will even work for arrays. If you want to report errors right in the signature, you can combine it with traits.


std containers with signature like std::vector (not recommended)

The simplest solution is approximated by Kerrek SB already, though it is invalid C++. The corrected variant goes like so:

#include <memory> // for std::allocator
template <template <typename, typename> class Container, 
          typename Value,
          typename Allocator=std::allocator<Value> >
void bar(const Container<Value, Allocator> & c, const Value & t)
{
  //
}

However: this will only work for containers that have exactly two template type arguments, so will fail miserably for std::map (thanks Luc Danton).


Any kind of secondary template arguments (not recommended)

The corrected version for any secondary parameter count is as follows:

#include <memory> // for std::allocator<>

template <template <typename, typename...> class Container, 
          typename Value,
          typename... AddParams >
void bar(const Container<Value, AddParams...> & c, const Value & t)
{
  //
}

template <typename T>
class OneParameterVector {};

#include <vector>
int main () {
    OneParameterVector<float> b;
    bar (b, 1.2f);
    std::vector<float> c;
    bar (c, 1.2f);
}

However: this will still fail for non-template containers (thanks Luc Danton).

这篇关于c++ 模板类;具有任意容器类型的函数,如何定义它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆