gpt4 book ai didi

c++ - 未自动确定的模板化类型的隐式转换运算符

转载 作者:太空狗 更新时间:2023-10-29 20:33:04 25 4
gpt4 key购买 nike

我有一个模板类 thing使用隐式转换运算符,如下所示:

#include <stdio.h>

template <typename T>
struct thing
{
T t;

operator const T&() const
{
return t;
}
};

template <typename T>
struct B
{
T t;
};

void fun(const int&) {
printf("int\n");
}

template <typename T>
void fun(const B<T>&) {
printf("B<T>\n");
}

int main()
{
thing<int> a;
fun(a);

thing<B<int>> b;
fun(b);

return 0;
}

调用 fun(const int&)thing<int> ,编译器能够找出调用隐式转换运算符以传递 const T& (在本例中为 const int& )到 fun(const int&) .

然而,对于 thing<B<int>> ,编译器无法弄清楚我期望 fun(const B<T>&)被调用。

我如何帮助编译器解决这个问题而不转换 bconst B<int>&明确地(例如使用 static_cast<const B<int>&>(b))?

我的具体使用场景类似于我使用的约束提供的代码B有 ~10 种不同的类型 T ,即不是任意的很多不同的 T秒。如果我必须创建 ~10 个模板特化,那就这样吧。但是,我不知道如何最好地重载 struct B在这种情况下。但也许我走错了路 - 是否存在更简单/更优雅的解决方案?

最佳答案

How can I help the compiler figuring this out without casting b to const B<int>&?

你不能。模板不进行任何隐式转换。他们推断出参数的类型,这就是他们使用的类型。

您可以做的一件事是向您的包装器添加一个获取函数,例如

template <typename T>
struct thing
{
T t;

operator const T&() const
{
return t;
}
const T& get() const
{
return t;
}
};

然后您可以调用fun喜欢

fun(b.get());

关于c++ - 未自动确定的模板化类型的隐式转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57414924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com