小编Bas*_*sti的帖子

如何使用三向比较(spaceship op)实现不同类型之间的operator==?

简单任务:我有这两种类型

struct type_a{
   int member;
};

struct type_b{
   int member;
};
Run Code Online (Sandbox Code Playgroud)

我想使用这个新的 C++20 太空飞船操作,每个人都说它太酷了,能够编写type_a{} == type_b{}. 我没能做到这一点。即使我operator<=>在它们之间写,我也只能调用type_a{} <=> type_b{},而不能进行简单的比较。这让我感到困惑,因为只有一个类,三向比较也定义了所有其他类。

替代配方?怎样才能做到这一点std::three_way_comparable_with<type_a, type_b>呢?

c++ spaceship-operator c++20

3
推荐指数
1
解决办法
615
查看次数

如何使用具有运行时类型的编译时接口?

我有一个函数,它接受 aT并在提供的对象上调用特定的函数。到目前为止,它是从编译时对象中使用的,所以一切都很好。最小的例子:

#include <iostream>

struct A {
   void fun() const { std::cout << "A" << std::endl; }
};

struct B {
   void fun() const { std::cout << "B" << std::endl; }
};

template<class T>
void use_function(const T& param) {
   param.fun();
}

int main() {
   use_function(A{}); // "A"
   use_function(B{}); // "B"
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在我试图将它use_function()与在运行时创建的对象一起使用并且很难。我不能使用std::variant或者std::any因为我需要为它们的访问函数提供类型作为模板参数 - 尽管它们的所有变体都满足函数接口。(失败的)变体方法的示例:

using var_type = std::variant<A, B>;

struct IdentityVisitor {
   template<class T>
   auto operator()(const T& alternative) …
Run Code Online (Sandbox Code Playgroud)

c++ templates variant

1
推荐指数
1
解决办法
61
查看次数

给定一个模板化类,有没有办法获得“基本”/非模板化类型?

很简单,但也许不可能:给定一些T<some_type>,有没有办法得到T?这里有一个更好的代码示例:

template<class T>
struct parametrized_class{
   
};

template<class T>
using make_floaty = T<float>; // this doesn't compile since T is not the "base" type

int main() {
   using int_class = parametrized_class<int>;
   using float_class = make_floaty<int_class>;
}
Run Code Online (Sandbox Code Playgroud)

我不认为是这样,但我想确定一下。

c++

1
推荐指数
1
解决办法
52
查看次数

具有重复类型的 C++ 可变参数模板

是否可以编写可变参数模板或折叠表达式,其中函数签名可以是这样的

void f(int, string, int, string, ...)
Run Code Online (Sandbox Code Playgroud)

这种风格在 Python 中非常流行且用户友好,但我无法在 C++ 中使用它。特别是,我会使用它来为绘图函数提供数据,后跟一个标签。

编辑:为了扩展,我想这样调用函数:

f(5, "first number");
f(5, "first number", 6, "second number");
Run Code Online (Sandbox Code Playgroud)

并带有 4、6 或 ... 2*n 个参数。

c++ templates variadic-templates

0
推荐指数
1
解决办法
74
查看次数