我正在尝试创建一个ElementIterable可以确定类型是否为嵌套范围的概念。例如,in 中的元素std::vector<int>不可迭代,但std::vector<int>in 中的元素 ( )std::vector<std::vector<int>>是可迭代的。我想到了使用的想法std::iterator_traits<T>,实验代码如下。然而,这个ElementIterable概念并不像预期的行为那样工作。有什么想法可以解决这个ElementIterable概念吗?
template<typename T>
concept ElementIterable = requires(typename std::iterator_traits<T>::value_type x) // requires-expression
{
x.begin(); // must have `x.begin()`
x.end(); // and `x.end()`
};
Run Code Online (Sandbox Code Playgroud)
这个的用法ElementIterable是here。
template<typename T> requires ElementIterable<T>
void Foo(T input);
template<typename T> requires ElementIterable<T>
void Foo(T input)
{
std::cout << "Element iterable" << std::endl;
}
template<typename T>
void Foo(T input);
template<typename T>
void Foo(T input)
{
std::cout << "Element not …Run Code Online (Sandbox Code Playgroud) 我正在尝试std::iter_value_t使用 C++20 概念实现递归版本,以便可以检索T类似嵌套容器的基本类型std::vector<std::vector<...std::vector<T>...>>。实验实现如下。
template<typename T>
concept is_iterable = requires(T x)
{
*std::begin(x);
std::end(x);
};
template<typename T> requires (!is_iterable<T>)
struct recursive_iter_value_t_detail
{
typedef typename T type;
};
template<typename T> requires (is_iterable<T>)
struct recursive_iter_value_t_detail
{
typedef typename std::iter_value_t<typename recursive_iter_value_t_detail<T>::type> type;
};
template<typename T>
using recursive_iter_value_t = typename recursive_iter_value_t_detail<T>::type;
Run Code Online (Sandbox Code Playgroud)
尝试编译此代码后,'recursive_iter_value_t_detail': requires clause is incompatible with the declaration弹出了唯一的错误消息,我不确定是什么requires clause is incompatible with the declaration意思。是不是template struct 不能像这样重载的问题?请帮我解决这个问题。
的预期输出recursive_iter_value_t<std::vector<std::vector<int>>>为int。
我已经检查了链接“为什么我不能在 C# 中将“this”设置为一个值?我知道这this是只读的。换句话说,它(内容)不能分配给另一个新对象。我只是想知道 C# 中这种约束的哲学或考虑。如果是为了内存管理的安全性,C#使用垃圾收集器来确定一个对象以后的使用情况。
public class TestClass
{
private int Number;
public TestClass()
{
this.Number = 0;
}
public TestClass(TestClass NewTestClass)
{
this = NewTestClass; // CS1604 Cannot assign to 'this' because it is read-only
}
}
Run Code Online (Sandbox Code Playgroud)
这样一来,看来成员需要一一更新了。
public class TestClass
{
private int Number;
public TestClass()
{
this.Number = 0;
}
public TestClass(TestClass NewTestClass)
{
this = NewTestClass; // CS1604 Cannot assign to 'this' because it is read-only
}
}
Run Code Online (Sandbox Code Playgroud)
欢迎提出任何意见。
注意:为了澄清起见,C++ 部分已被删除。