tuple_size 和一个从元组继承的类?

2022-01-20 00:00:00 tuples compiler-errors templates c++ c++11

我有以下代码:

class TR_AgentInfo : public tuple<
                              long long,         //AgentId
                              string,         //AgentIp
                              >
{
public:
TR_AgentInfo() {}
TR_AgentInfo(
  const long long& AgentId,
  const string& AgentIp,
   )
{
    get<0>(*this) = AgentId;
    get<1>(*this) = AgentIp;
}

long long getAgentId() const { return get<0>(*this); }
void setAgentId(const long long& AgentId) { get<0>(*this) = AgentId; }

string getAgentIp() const { return get<1>(*this); }
void setAgentIp(const string& AgentIp) { get<1>(*this) = AgentIp; }
};

现在我想使用这段代码:

Now I want to use this code:

int count = tuple_size<TR_AgentInfo>::value;

但是 gcc 给出了这个错误:

but gcc give this error:

error: incomplete type std::tuple_size<TR_AgentInfo> used in nested name specifier

现在我该怎么办?

推荐答案

如果你只是想让你的一个类使用 std::tuple_size,你可以简单地提供一个专业化:

If you just want your one class to work with std::tuple_size, you can simply provide a specialization:

namespace std
{
  template<> struct tuple_size<TR_AgentInfo>
  {
    static const size_t value = 2;

    // alternatively, `tuple_size<tuple<long long, string>>::value`
    // or even better, `tuple_size<TR_AgentInfo::tuple_type>::value`, #1
  };
}

明确允许您向命名空间 std 添加特化,正是针对您的情况.

You are expressly allowed to add specializations to the namespace std, precisely for situations like yours.

如果您的实际类本身是模板化的,您可以简单地将 2 替换为适当的构造.例如,对于建议 #1,您可以将 tuple_type 的 typedef 添加到您的类中.给这只猫剥皮的方法有很多.

If your actual class is itself templated, you can simply replace 2 by an appropriate construction. For example, for suggestion #1 you could add a typedef for tuple_type to your class. There are many ways to skin this cat.

相关文章