gpt4 book ai didi

c++ - 打印非类型模板内部类

转载 作者:太空狗 更新时间:2023-10-29 23:01:45 25 4
gpt4 key购买 nike

我有一个非类型类模板(例如 Counted),它指向类模板的一个实例(例如 Counter)。只要两个模板类都是兄弟,一切都可以正常工作,例如编写一个打印操作符。

现在由于几个原因,我想将 Counted 作为内部类移到 Counter 内部,但我发现自己无法编写打印运算符。

Here's a working "sibling class" version , 主要代码在这里:

template < class Count >
struct Counter {
using count_type = Count;
count_type instances = 0;
};

template < class Cnt, Cnt& c>
struct Counted {
using id_type = typename Cnt::count_type;
id_type id;
Counted() : id(c.instances) { ++c.instances; }
~Counted() { --c.instances; }
};

template < class Cnt, Cnt& c >
std::ostream& operator<<(std::ostream& os, Counted<Cnt,c> sib) {
os << "printing sibling " << sib.id;
return os;
}

using SCounter = Counter<std::size_t>;
SCounter sc;
using SCounted = Counted<SCounter, sc>;

Here's the not compiling "inner class" version主要代码在这里:

template < class Count >
struct Counter {
using count_type = Count;
count_type instances = 0;

template <Counter& c>
struct Counted {
using id_type = count_type;
id_type id;
Counted() : id(c.instances) { ++c.instances; }
~Counted() { --c.instances; }
};
};

template < class Count, Counter<Count>& c >
std::ostream& operator<<(std::ostream& os,
typename Counter<Count>::template Counted<c>& sib) {
os << "printing inner " << sib.id;
return os;
}

using SCounter = Counter<std::size_t>;
SCounter sc;
using SCounted = SCounter::Counted<sc>;

错误:

prog.cpp: In function 'int main()':
prog.cpp:32:15: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
std::cout << j << std::endl;
^
In file included from /usr/include/c++/4.9/iostream:39:0,
from prog.cpp:1:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = Counter<unsigned int>::Counted<(* & sc)>]'
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
^

我的代码、我的编译器是否有问题,或者这是标准不允许的?

最佳答案

Koenig 运算符就是您想要的:

  template <Counter& c>
struct Counted {
using id_type = count_type;
id_type id;
Counted() : id(c.instances) { ++c.instances; }
~Counted() { --c.instances; }

friend std::ostream& operator<<(
std::ostream& os,
Counted const& sib
) {
os << "printing inner " << sib.id;
return os;
}
};
};

这里我们创建一个 friend operator<< .当您尝试使用 << 时,它将通过 ADL(或 Koenig 查找)找到用Counted实例。

为每种类型的 Counted 创建了一个不同的函数,并且没有进行模板推导。 .

关于c++ - 打印非类型模板内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30373154/

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