gpt4 book ai didi

c++ - 使用模板化声明时可能丢失基本对象的方法

转载 作者:太空宇宙 更新时间:2023-11-04 13:53:52 29 4
gpt4 key购买 nike

这是该线程中答案的应用。 How do I return the largest type in a list of types?

其中模板允许定义一个类型,该类型是两个对象的最大值。

从编译器的错误信息来看,我不知何故失去了 int 的方法。

代码如下:

#include <iostream>

template<typename A>
struct givenType {
typedef A type;
};

template<typename A, typename B>
struct largestType {
typedef typename givenType<std::conditional<sizeof(A) <= sizeof(B), B, A >>::type type;
};


template<typename T1, typename T2>
class Alpha {
public:
typedef typename largestType<T1,T2>::type bigT3;
Alpha() {};

bigT3 answer(void) {
bigT3 t;
return t;
}

void tryCout(void) {
std::cout << answer() << std::endl;
}

};

int _tmain(int argc, _TCHAR* argv[])
{
Alpha<int,int> a;
a.tryCout();
return 0;
}

伴随着以下错误:

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::conditional<_Test,_Ty1,_Ty2>' (or there are no acceptable conversion) with

[
_Test=true,
_Ty1=int,
_Ty2=int
]

谢谢。

最佳答案

您正在尝试将整个 std::conditional 结构发送到 std::cout(Big3 现在与 std::conditional 类型定义为 int)。

std::conditional 通过其 typedef type 为您提供所选类型。你应该使用它。

typename std::conditional<sizeof(A) <= sizeof(B), B, A>::type
^^^^

所以整个事情应该看起来像

template<typename A, typename B>
struct largestType {
typedef typename givenType<
typename
std::conditional<
sizeof(A) <= sizeof(B)
, B
, A
>::type // You missed this type
>::type type;
};

但是,您实际上并不需要 givenType 模板结构。你可以只使用 conditional

中的那个
template<typename A, typename B>
struct largestType {
typedef typename
std::conditional<
sizeof(A) <= sizeof(B)
, B
, A
>::type type;
};

或者只是

template<typename T1, typename T2>
class Alpha {
public:
typedef typename
std::conditional<
sizeof(T1) <= sizeof(T2)
, T2
, T1
>::type bigT3;

关于c++ - 使用模板化声明时可能丢失基本对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22391263/

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