我正在努力使最简单的示例发挥作用。这是我的代码:
// example.cpp
#include <pybind11/pybind11.h>
namespace py = pybind11;
class B {
public:
int b;
};
class A {
public:
int a;
A(int a) :a(a) {}
A(B b) { a = b.b; }
};
void fn(A) {}
PYBIND11_MODULE(example, m) {
py::class_<A>(m, "A")
.def(
py::init<int>(),
py::arg("a") = 1
);
py::class_<B>(m, "B")
.def(
py::init<int>(),
py::arg("b") = 2
);
py::implicitly_convertible<A, B>();
m.def("fn", &fn,
py::arg("a")
);
}
Run Code Online (Sandbox Code Playgroud)
# test.py
from example import *
a = A()
b = B()
fn(b)
Run Code Online (Sandbox Code Playgroud)
它构建得很好,但输出是:
$ python3.9 test.py …Run Code Online (Sandbox Code Playgroud) 我想要一个代表具有某种维度的单位的类。这应该表示 1.5m^2 之类的东西。应允许与某种类型进行标量乘法,并且无量纲单位的行为应与基础类型完全相同。这是我的解决方案:
#include <type_traits>
template<typename T, int Dim>
class Unit {
public:
explicit Unit(T t): _value(t) {}
template<int D = Dim, typename std::enable_if_t<D==0, int> = 0>
operator T() { static_assert(Dim==0, ""); return _value; } //static_assert not necessary, but gives error if template is removed
T _value;
};
template<typename S, typename T, int Dim>
auto operator*(S s, Unit<T,Dim> unit)
{
return Unit<T, Dim>(s * unit._value);
}
auto main() -> int
{
auto i = double{0};
//Scalar test
auto scalar = …Run Code Online (Sandbox Code Playgroud) template<typename Integral>
struct IntegralWrapper {
Integral _value;
IntegralWrapper() = default;
IntegralWrapper(Integral value)
: _value(value) {}
operator Integral() const {
return _value;
}
operator bool() const = delete;
};
int main() {
IntegralWrapper<int> i1, i2;
i1 * i2;
}
Run Code Online (Sandbox Code Playgroud)
gcc 编译成功,但 MSVC 和 clang 编译失败,错误overloaded operator '*' is ambiguous。问题来自于显式删除operator bool。
https://godbolt.org/z/nh6M11d98
哪一方(gcc 或 clang/MSVC)是正确的?为什么?
c++ operator-overloading language-lawyer implicit-conversion
我正在学习智能指针,以下示例test.cpp
#include<iostream>
#include<vector>
#include<memory>
struct abstractShape
{
virtual void Print() const=0;
};
struct Square: public abstractShape
{
void Print() const override{
std::cout<<"Square\n";
}
};
int main(){
std::vector<std::unique_ptr<abstractShape>> shapes;
shapes.push_back(new Square);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码有编译错误“c++ -std=c++11 test.cpp”:
smart_pointers_2.cpp:19:12: error: no matching member function for call to 'push_back'
shapes.push_back(new Square);
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解释一下这个错误吗?顺便说一句,当我更改push_back为时emplace_back,编译器仅给出警告。
class X{
public:
X(){}
};
class Y{
public:
Y(X x) { std::cout << "Temporary created!"; }
};
int main(){
X x;
const Y& y = x;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么Y在这里创建临时对象(类型为 )?我理解在这种情况下临时对象的必要性,但我不明白标准对此有何说明。如果我们看一下标准,如果我没有记错的话,唯一适合我们这里情况的情况就是绑定对纯右值的引用。x那么, in 中的子表达式是否const Y& y = x被转换为纯右值,或者这里发生了什么其他事情?
我还查看了lvalue -> rvalue conversion,但整个事情似乎解释不清。它没有说明发生这种类型转换的场景。据我所知,这种转变发生的次数比我想象的要多。例如,如果我们看一下cpp.reference 上的隐式转换,几乎每个部分都以“XXX 类型的纯右值可以转换为 YYY...”开头,这表明我们在隐式转换中大多数时候使用左值->右值转换作为某种基本转换。密切相关的是,我也研究了这个主题,这可能是对整个情况的一个很好的看法,但也可能相当过时。
基本上,我有两个问题。标题中的第一个和(可能不相关)第二个:左值 -> 右值转换何时实际发生?
编辑:关于我的第一个问题(来自标题),我已经发展了一种我认为与草案相符的理论。基本上,表达式x被转换为类型的纯右值const Y,但不创建任何对象。之后,我们绑定了纯右值,这会导致临时物化将纯右值转换为 xvalue。只有这样我们才能绑定const对该临时对象的引用。我离真相有多远?
常规静态分配数组如下所示,可以使用以下公式进行访问:
const int N = 3;
const int M = 3;
int a1[N][M] = { {0,1,2}, {3,4,5}, {6,7,8} };
int x = a1[1][2]; // x = 5
int y = *(a1+2+N*1); // y = 5, this is what [] operator is doing in the background
Run Code Online (Sandbox Code Playgroud)
数组是连续的内存区域。在动态数组分配的情况下看起来有所不同,而是有指向数组的指针数组:
int** a2 = new int*[N];
for (int i = 0; i < N; i++)
a2[i] = new int[M];
//Assignment of values as in previous example
int x = a2[1][2];
int y = *(*(a2+1))+2); // …Run Code Online (Sandbox Code Playgroud) c c++ pointer-arithmetic multidimensional-array implicit-conversion
在 C++ 中,我正在寻找标准的关键部分\n解释我在该语言的两个指向成员的指针访问运算符之间观察到的行为的细微差别,.*以及->*。
根据下面显示的我的测试程序,虽然->*似乎允许其\n右手表达式是任何类型隐式转换为 \n pointer to member of S,.*但事实并非如此。当使用 ngcc 和 clang 进行编译时,两个编译器都会对标记为 \'(2)\' 的行产生错误,表明我的类Offset不能用作成员指针。
测试程序\n https://godbolt.org/z/46nMPvKxE
\n#include <iostream>\n\nstruct S { int m; };\n\ntemplate<typename C, typename M>\nstruct Offset\n{\n M C::* value;\n operator M C::* () { return value; } // implicit conversion function\n};\n\nint main()\n{\n S s{42};\n S* ps = &s;\n Offset<S, int> offset{&S::m};\n\n std::cout << ps->*offset << \'\\n\'; // (1) ok\n std::cout << s.*offset …Run Code Online (Sandbox Code Playgroud) std::atomic_fetch_add()对于低于 9.0 的 x86-64 clang 版本和低于 9.1 的 gcc 版本,以下涉及调用模板函数的小型 C++ 程序无法在 godbolt 中编译,在这两种情况下都使用该--std=c++11选项。
#include <iostream>
#include <atomic>
std::atomic<char> ch ('@');
int main ()
{
std::atomic_fetch_add (&ch, 5);
std::cout << ch << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
在那些早期的编译器版本中(它可能与编译器提供的 C++ 库更相关,我不确定),调用std::atomic_fetch_add (&ch, 5); 无法匹配原子获取函数的任何模板专门化,因为chis的类型char和类型是:5int
:在函数“int main()”中::8:34:错误:没有匹配的函数可调用“atomic_fetch_add(std::atomic*, int)”std::atomic_fetch_add (&ch, 5); ...
但是,更高版本的编译器(和库?)成功编译了此用法。
我几乎是一个 C++ 初学者,但我认为这与在确定要使用的适当模板专业化过程中未执行隐式转换有关。(我可能没有使用精确的语言。)
我知道我可以通过将其重写为来修改对工作的调用
std::atomic_fetch_add<char> (&ch, 5);
Run Code Online (Sandbox Code Playgroud)
或者
std::atomic_fetch_add (&ch, (char)5);
Run Code Online (Sandbox Code Playgroud)
但是,我有兴趣获得一个版本的<atomic>库来支持使用,而无需显式实例化和强制转换。(编译器是 clang 15.0.0,--std=c++11该库是 …
我偶然发现了与range一起operator<<使用时存在不明确重载的问题。\n更具体地说,使用以下代码:std::views::enumeratesize_t
#include <iostream>\n#include <ranges>\nnamespace rv = std::ranges::views;\n\nint main()\n{\n for (const auto& [idx, value] : rv::iota(0zu, 5zu) | rv::enumerate)\n std::cout << idx << '\\n';\n}\nRun Code Online (Sandbox Code Playgroud)\n并gcc 13.1.1在 Linux 上使用以下命令进行编译:g++ --std=c++23 main.cpp.\n我收到错误:
main.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\nmain.cpp:11:19: error: ambiguous overload for \xe2\x80\x98operator<<\xe2\x80\x99 (operand types are \xe2\x80\x98std::ostream\xe2\x80\x99 {aka \xe2\x80\x98std::basic_ostream<char>\xe2\x80\x99} and \xe2\x80\x98std::tuple_element<0, const std::tuple<__int128, long unsigned int> >::type\xe2\x80\x99 {aka \xe2\x80\x98const __int128\xe2\x80\x99})\n 11 | std::cout << idx << '\\n';\n | ~~~~~~~~~ ^~ ~\n | | …Run Code Online (Sandbox Code Playgroud) 我有一个可以隐式转换为函数可接受的类型的结构std::map::insert()。
我按原样使用结构,但出现编译错误:
没有重载函数可以转换所有参数类型
但是,如果我使用显式转换结构static_cast,它会被接受。
我的问题是,为什么隐式转换在这里不起作用?
示例代码:
struct MyStruct
{
MyStruct(std::string s, int i) : data(s, i) {}
operator std::pair<std::string, int>() const
{
return data;
}
private:
std::pair<std::string, int> data;
};
MyStruct my_val1("hello", 4);
MyStruct my_val2("world", 2);
std::map<std::string, int> my_map {};
my_map.insert(static_cast<std::pair<std::string, int>>(my_val1)); // compiles
my_map.insert(my_val2); // not compiles
Run Code Online (Sandbox Code Playgroud)