C ++数组下标运算符模板 [英] C++ Array Subscript Operator Template

查看:167
本文介绍了C ++数组下标运算符模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试访问一个存储类稍微容易一点,我最终在一个情况,我没有很多的知识。而且,发现那些试图做同样事情的人并不容易。

After trying to make access to a storage class a little easier, I ended up in a situation that I don't have a lot of knowledge on. And, finding people that are trying to do the same thing as me isn't easy.

我想做的是,有一个存储数组的类的值作为字符串在内部,但允许从用户端进行简单类型转换。我计划做的是使用数组下标运算符返回通过模板指定的任何类型。虽然,它听起来好多比它在实践中工作。

What I'm trying to do, is have a class that stores an array of values as strings internally, but allows simple type casting from the user's end. What I had planned on doing is use the array subscript operator to return whichever type they specify through a template. Although, it sounds a lot better than it works in practice. Here's a simple example of what I'm doing, to give you an idea of how it should work.

class StringList
{
    public:
    template <typename T> 
    T operator[](const int i)
}

我将定义一些特定的模板,并且任何用户可以很容易地定义更多,如果需要。但是,最大的问题是,我不知道如何使用模板调用下标运算符。起初,我假定以下(显然是不正确的),考虑它类似于调用模板方法的标准方法。

From there, I would define a few specific templates, and any user could very easily define more if needed. But, the biggest problem with this is, I don't know how to call the subscript operator with a template. At first I assumed the following(which apparently isn't correct), considering it's similar to the standard way of calling a template method.

StringList list;
T var = list<T>[0];

有没有人知道调用下标运算符作为模板的正确方法?或者,我应该避免这样做,并使用命名方法?

Does anyone know the proper way of calling the subscript operator as a template? Or, should I just avoid doing this, and use a named method?

推荐答案

调用你的操作符的唯一方法是明确写 list.operator []< T>()

The only way calling your operator is explicitly writing list.operator[]<T>().

有两种基本方法:


  1. 编写一个函数模板,如 list.get< int>()(由templatetypedef提议)

  2. 将自动对话的代理传回 T

  1. Write a function template like list.get<int>() (as proposed by templatetypedef)
  2. Return a proxy with automatic conversation to T.


b $ b

代码如下:

The code would look like:

// in the class
struct proxy {
  proxy(StringList *list, int i) : list(list), i(i) {}
  StringList *list;
  int i;
  template <typename T>
  operator T() { return list->get<T>(i); }
};

proxy operator[](int i) { return proxy(this, i); }

template <typename T> 
T get(int i) { return ...; T(); }

// how to use it:
StringList list;
int var = list.get<int>(0);
float var2 = list[0];

这篇关于C ++数组下标运算符模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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