简单任务:我有这两种类型
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>呢?
我有一个函数,它接受 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) 很简单,但也许不可能:给定一些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)
我不认为是这样,但我想确定一下。
是否可以编写可变参数模板或折叠表达式,其中函数签名可以是这样的
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 个参数。