使用模板化声明时,可能会丢失基本对象上的方法

Possible loss of method on basic objects when using templated declaration

本文关键字:对象 方法 声明      更新时间:2023-10-16

这是这个线程的答案的一个应用。如何返回类型列表中最大的类型?

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

从编译器的错误信息来看,我不知何故失去了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;
}

和下面的错误:

错误C2679:二进制'<<':找不到右操作数类型为'std::conditional<_Test,_Ty1,_Ty2>'的操作符(或者不接受转换)

[
    _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++编译器转换为左移操作符,在该上下文中完全没有意义(因此是不可理解的错误消息的来源)。将<<替换为< <(中间有空格)