gpt4 book ai didi

c++ - 如何声明实例化 `emplace()` 的 `std::set` 的返回?

转载 作者:行者123 更新时间:2023-11-28 04:39:33 24 4
gpt4 key购买 nike

场景

  1. 我有一个类模板:

    template<class idxT>
    class SimpleGraph {
    private:
    // ...
    std::set<std::pair<idxT,idxT>> edgeSet;
    // ...
    void addEdge(idxT a, idxT b);
    // ...
    }
  2. 我需要在addEdge()中使用edgeSet.emplace(a,b)的返回,记为r以下内容。
  3. r的声明和赋值需要分开,因为ab的值是由if决定的-else 语句。因此,我不能使用

    auto r = edgeSet.emplace(a,b);
  4. 我尝试了以下策略,但均未成功。第一个是

    std::pair<decltype(edgeSet)::iterator,bool> r;
    // some code
    r = edgeSet.emplace(a,b);

    第二个是

    // inside class template
    typedef std::set<std::pair<idxT,idxT>> EdgeSetType;
    EdgeSetType edgeSet;

    // inside definition of `addEdge()`
    std::pair<EdgeSetType::iterator,bool> r;
    // some code
    r = edgeSet.emplace(a,b);

问题

如何声明 edgeSet.emplace(a,b) 的返回?

更新 1:第一次试验的可验证示例

#include <set>      // set
#include <utility> // pair
#include <iostream>

template<class idxT>
class SimpleGraph {
public:
void test(void);

private:
std::set<std::pair<idxT,idxT>> edgeSet;
void addEdge(idxT a, idxT b);
};

template<class idxT>
void SimpleGraph<idxT>::test(void) {
addEdge(1,2);
addEdge(1,2);
}

template<class idxT>
void SimpleGraph<idxT>::addEdge(idxT a, idxT b) {

std::pair<decltype(edgeSet)::iterator,bool> r;

if (a < b) {
r = edgeSet.emplace(a,b);
}
else {
r = edgeSet.emplace(a,b);
}
if (!r.second) {
std::cerr << "Error on (" << a << ',' << b <<"): "
<< "mutiple edges are not allowed for a simple graph.\n";
exit(1);
}
}

int main(void) {
SimpleGraph<int> graph;
graph.test();
}

clang 提示

test.cpp:24:13: error: template argument for template type parameter must be a type; did you forget 'typename'?
std::pair<decltype(edgeSet)::iterator,bool> r;

另见 here对于 gcc 生成的编译时错误。

最佳答案

clang++ 编译器实际上是在用“你忘记了‘typename’吗?”来暗示解决方案

由于 decltype(edgeSet) 是类型依赖的(它间接依赖于模板参数 idxT),编译器不能在第一次解析模板,因此 C++ 表示将 decltype(edgeSet):: 之后的任何名称假定为变量或函数。由于它确实是一种类型,因此您需要使用关键字 typename 告诉 C++:

std::pair<typename decltype(edgeSet)::iterator,bool> r;

更多细节在问题的答案中 Where and why do I have to put the “template” and “typename” keywords?

或者,注意任何有效的表达式都可以在 decltype 中使用。 (这是一个未计算的上下文,这意味着如果您使用函数调用、隐式转换等,实际上不会为该表达式调用任何函数。)所以您也可以这样做:

decltype(edgeSet.emplace(a,b)) r;

关于c++ - 如何声明实例化 `emplace()` 的 `std::set` 的返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50541771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com