当我发现标准定义std::unique_ptr并且std::shared_ptr以两种完全不同的方式关于指针可能拥有的Deleter时,我认为这很奇怪.这是来自cppreference :: unique_ptr和cppreference :: shared_ptr的声明:
template<
class T,
class Deleter = std::default_delete<T>
> class unique_ptr;
template< class T > class shared_ptr;
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,unique_ptr将"Deleter"对象的类型"保存"为模板参数.这也可以通过稍后从指针中检索Deleter的方式看出:
// unique_ptr has a member function to retrieve the Deleter
template<
class T,
class Deleter = std::default_delete<T>
>
Deleter& unique_ptr<T, Deleter>::get_deleter();
// For shared_ptr this is not a member function
template<class Deleter, class T>
Deleter* get_deleter(const std::shared_ptr<T>& p);
Run Code Online (Sandbox Code Playgroud)
有人可以解释这种差异背后的理性吗?我明显赞成这个概念,unique_ptr为什么这不适用于此shared_ptr?另外,为什么get_deleter在后一种情况下会成为非成员函数呢?
我试图从矢量中删除一些元素,基于谓词,并收集结果.这是一个具有预期结果的(不工作)示例:
let mut v: Vec<i32> = vec![1, 2, 3, 4, 5, 6];
let drained: Vec<i32> = v.iter().filter(|e| (*e) % 2 == 0).drain(..).collect();
assert_eq!(v, vec![1, 3, 5]);
assert_eq!(drained, vec![2, 4, 6]);
Run Code Online (Sandbox Code Playgroud)
这导致错误
error[E0599]: no method named `drain` found for type `std::iter::Filter<std::slice::Iter<'_, i32>, [closure@src/main.rs:4:45: 4:62]>` in the current scope
--> src/main.rs:4:64
|
4 | let drained: Vec<i32> = v.iter().filter(|e| (*e) % 2 == 0).drain(..).collect();
| ^^^^^
Run Code Online (Sandbox Code Playgroud)
我看过几种不同的选择,它们似乎都没有做我想做的事情:
Vec::retain 从向量中删除元素,但不会返回已删除元素的所有权.
v.drain(..).filter(condition).collect()返回正确的值,drained但清空整个向量.
最近从这个问题我得知以下似乎是合法的java:
class Bar {
void foo(Bar this) {}
}
Run Code Online (Sandbox Code Playgroud)
现在,我试图找到java标准中的哪个位置表示你可以这样做,并且在这里查看但我找不到该部分.
有人可以引用它允许这种形式的方法声明的地方以及声明命名参数的限制this是什么?
我有一个实现的草图:
trait Listener {
fn some_action(&mut self);
fn commit(self);
}
struct FooListener {}
impl Listener for FooListener {
fn some_action(&mut self) {
println!("{:?}", "Action!!");
}
fn commit(self) {
println!("{:?}", "Commit");
}
}
struct Transaction {
listeners: Vec<Box<Listener>>,
}
impl Transaction {
fn commit(self) {
// How would I consume the listeners and call commit() on each of them?
}
}
fn listener() {
let transaction = Transaction {
listeners: vec![Box::new(FooListener {})],
};
transaction.commit();
}
Run Code Online (Sandbox Code Playgroud)
我可以Transaction在它们上面使用侦听器,当事务发生时会调用侦听器.既然Listener是特质,我会存储一个Vec<Box<Listener>> …
在这里阅读库代码时,我注意到一个看起来非常奇怪的语法,我无法理解:
momenta
:: (KnownNat m, KnownNat n)
=> System m n
-> Config n
-> R n
momenta Sys{..} Cfg{..} = tr j #> diag _sysInertia #> j #> cfgVelocities
-- ^^^^^^^^^^^^^^^ the syntax in question
where
j = _sysJacobian cfgPositions
Run Code Online (Sandbox Code Playgroud)
相关的定义System包括一个记录{ _sysJacobian :: R n -> L m n },并且{ cfgVelocities :: R n }是记录声明的一部分Config所以我相信我知道代码的作用,我认为代码是相当可读的,是作者的道具.
问题是:这个语法叫什么,我怎么能用它?
我认为地图和reference_wrappers会变得容易,但我绊倒了一些奇怪的东西:
#include <map>
#include <functional>
int main(void) {
std::map<int, std::reference_wrapper<const int>> mb;
const int a = 5;
mb[0] = std::cref(a);
}
Run Code Online (Sandbox Code Playgroud)
这段代码给了我以下编译器错误:
In file included from c:/MinGW/x86_64-w64-mingw32/include/c++/bits/stl_map.h:63:0,
from c:/MinGW/x86_64-w64-mingw32/include/c++/map:61,
from ../test/main.cpp:9:
c:/MinGW/x86_64-w64-mingw32/include/c++/tuple: In instantiation of 'std::pair<_T1, _T2>::pair(std::tuple<_Args1 ...>&, std::tuple<_Args2 ...>&, std::_Index_tuple<_Indexes1 ...>, std::_Index_tuple<_Indexes2 ...>) [with _Args1 = {int&&}; long long unsigned int ..._Indexes1 = {0ull}; _Args2 = {}; long long unsigned int ..._Indexes2 = {}; _T1 = const int; _T2 = std::reference_wrapper<const int>]':
c:/MinGW/x86_64-w64-mingw32/include/c++/tuple:1083:63: required from 'std::pair<_T1, _T2>::pair(std::piecewise_construct_t, std::tuple<_Args1 ...>, …Run Code Online (Sandbox Code Playgroud) 我有一个设置,其中收集了多个要设置为包含目录的包含目录,如以下模拟所示:
add_library(testlib SHARED "")
set_target_properties(testlib PROPERTIES LINKER_LANGUAGE CXX)
list(APPEND includePath "/some/dir" "/some/other/dir")
target_include_directories(testlib PUBLIC
$<BUILD_INTERFACE:${includePath}>
)
Run Code Online (Sandbox Code Playgroud)
现在的问题是以下
get_target_property(debug testlib INTERFACE_INCLUDE_DIRECTORIES)
message("${debug}")
Run Code Online (Sandbox Code Playgroud)
版画
/home/user/test-proj/$<BUILD_INTERFACE:/some/dir;/some/other/dir>
Run Code Online (Sandbox Code Playgroud)
出于某种原因,项目的绝对路径位于include目录之前。这导致了cmake的宣告:
CMake Error in src/hypro/CMakeLists.txt:
Target "testlib" INTERFACE_INCLUDE_DIRECTORIES property contains path:
"/home/user/test-proj/"
which is prefixed in the source directory.
Run Code Online (Sandbox Code Playgroud)
我可以以某种方式使用列表$<BUILD_INTERFACE>吗?
有没有办法从两个const ::std::type_info对象中确定,让我们命名它们,B以及DD 描述的类型是否从类型 B 派生?
我问是因为我想删除我得到的对象的类型,但稍后能够检查它是否可以安全地提升。
void* data;
const ::std::type_info* D;
template<typename D>
void store(D&& object)
{
D = &typeid(object);
data = ::std::addressof(object);
}
template<typename B>
B& load()
{
// if(typeid(B) != (*D)) throw ::std::bad_cast{};
return *reinterpret_cast<B*>(data); // <- also problematic
}
Run Code Online (Sandbox Code Playgroud)
我希望能够像这样使用它:
class Base {};
class Derived : Base {};
Derived d;
store(d);
// ....
load<Base>();
Run Code Online (Sandbox Code Playgroud)
因此,只对 typeid 使用相等比较是不合适的。我很确定这可能以类似于 dynamic_cast 可以解决这个问题的方式成为可能。我想要的是,在每种情况下D&都可以指定B&允许 B 作为 - 的类型参数load()-D当时不知道。
我想使用python的C-API实现为C用python编写的库。在python中,我可以通过声明以下内容在模块中声明“常量”:
RED = "red" # Not really a constant, I know
BLUE = "blue" # but suitable, nevertheless
def solve(img_h):
# Awesome computations
return (RED, BLUE)[some_flag]
Run Code Online (Sandbox Code Playgroud)
然后,这些常量由模块提供的函数返回。我在C中做同样的事情有些麻烦。这是到目前为止我得到的:
PyMODINIT_FUNC
PyInit_puzzler(void)
{
PyObject* module = PyModule_Create(&Module);
(void) PyModule_AddStringConstant(module, "BLUE", "blue");
(void) PyModule_AddStringConstant(module, "RED", "red");
return module;
}
PyObject* solve(PyObject* module, PyObject* file_handle)
{
// Do some awesome computations based on the file
// Involves HUGE amounts of memory management, thus efficient in C
// PROBLEM: How do I return the StringConstants from …Run Code Online (Sandbox Code Playgroud) 在我的代码中,我(意外地)写了void.class(不是Void.class)编译器很高兴地接受了它.到现在为止,我认为这些原始物不是真正的物体(不仅是void,也在谈论int......等等),所以他们没有课.
我在谈论所有"原始阶级".每个原语类型具有由表示的类<primitivetype>.class,例如float.class
Class这种"原始阶级"是指什么" ",例如void.class?int.class.isInstance(2.3f)吗?