使用模板化声明时,可能会丢失基本对象上的方法
Possible loss of method on basic objects when using templated declaration
这是这个线程的答案的一个应用。如何返回类型列表中最大的类型?
,其中模板允许定义一个类型,该类型是两个对象的最大值。
从编译器的错误信息来看,我不知何故失去了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++编译器转换为左移操作符,在该上下文中完全没有意义(因此是不可理解的错误消息的来源)。将<<
替换为< <
(中间有空格)
相关文章:
- 使用std::函数映射对象方法
- 正在调用shared_ptr对象方法
- 检查哪个对象调用了另一个对象的对象方法
- 如何在C++中循环访问未知对象方法?
- c++ 替换调用对象方法的宏函数
- 我能否通过将函数实现为类对象方法来避免使用互斥锁
- 我可以制作一个对象方法,如果单独调用,它将自行修改,但如果在复制初始化期间调用,则会返回一个新对象?
- 如何让两个不同的对象方法相互用作参数
- 在创建 c++ 期间调用对象方法
- 扩展中的日期时间对象方法C++问题
- 将对象方法从向量应用于C 的第二个向量中的对象
- 将 C++/CLI 对象指针传递给本机对象方法
- 多态性的面向对象方法
- 将对象方法传递到变量
- C :使用Main中定义的对象方法的函数
- 有关使用矢量迭代器访问对象方法的问题
- 定义可以执行对象方法和独立函数的函数时出现问题
- 调用列表中子对象方法的最佳方法
- main.cpp:(.text+0x8f):对[对象方法]的未定义引用
- cpp 从需要超类对象的函数访问子类对象方法