【问题标题】:How to get a reference of a const vector element from template如何从模板中获取 const 向量元素的引用
【发布时间】:2018-06-21 22:49:31
【问题描述】:

我有这个main.cpp

std::string hw[] = { "Hello", "World" };
const array_appender<std::string> ha( hw, sizeof( hw ) / sizeof( hw[ 0 ] ) );

if ( /*with some other conditions*/ &( ha.at( 0 ) ) == hw )
{
  //some other stuff
}

我有这个模板:

template<typename T>
class array_appender {
public:
    array_appender(T* array, size_t size) {
        append(array, size);
    }

    void append(T* array, size_t size) {
        for( int idx = 0; idx < size; ++idx)
        {
            std::cout << "value of array: " << array[idx] << std::endl;
            data.add(array[idx]);
        }
    }

    T at(size_t index) const {
        return data[index];
    }

    size_t size() {
        return data.size();
    }

    const size_t size() const {
        return data.size();
    }

private:
    std::vector<T> data;
};

但由于上述情况,我得到了这个错误:

error: taking address of temporary [-fpermissive]

我搜索了这个,但在这种情况下,我找到的解决方案对我不起作用。感谢您的任何想法!

【问题讨论】:

  • 这个&amp;( ha.at( 0 ) ) == hw 应该做什么?你的at 返回一个值(引用会更自然),那么通过获取它的地址会得到什么?

标签: c++ templates constants


【解决方案1】:

当您调用 &amp;( ha.at( 0 ) 时,您正在获取临时变量 (h.at(0)) 的地址 (&)。

你可以试试std::string tmp = ha.at( 0 ),取tmp的地址,但是……字符串的地址不可能等于字符串数组!您正在将临时变量的地址与对象中成员的地址进行比较。你的意思是比较字符串吗?

【讨论】:

  • 是的,我想让这个条件返回 true。
  • 考虑` if ( ( ha.at( 0 ) ) == hw[0] )`
【解决方案2】:

array_appender&lt;T&gt;::at 返回T,它将是调用站点ha.at(0) 上的临时对象(右值)。然后你取它的地址&amp;ha.at(0),这是被禁止的,因此错误“取临时地址”。

通常,像at 这样的方法会返回对对象的引用,以便可以对其进行修改(当然,如果需要的话):

T & at(size_t index) const {
    return data[index];
}

那么,取这个左值的地址是一个有效的操作。

看看std::array::atstd::vector::atstd::map::at

【讨论】:

  • @kortealma 首先是什么让您认为std::vector&lt;T&gt; 会有一个名为add 的成员函数?
  • @kortealma 以防万一,您需要push_back - 它可以满足您的需求。并注意 artoonie 所说的:您实际上是将指针(内存地址)与两个单独的对象进行比较,无论对象的内容如何,​​它们都不相等。您可能想比较对象本身,而不是内存地址。
  • 您确定必须有参考吗?没有它对我有用,但对它不起作用。
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 2022-01-17
  • 2021-06-23
  • 2012-04-07
  • 2015-01-19
  • 1970-01-01
  • 2016-09-14
相关资源
最近更新 更多