我想知道在我的情况下使用什么更好,为什么。首先我听说使用 RTTI (typeid) 是不好的。任何人都可以解释为什么?如果我确切地知道类型,那么在运行时比较它们有什么问题?此外,是否有任何示例如何使用 boost::type_of?通过强大的谷歌搜索,我没有发现任何问题 :) 对我来说,其他解决方案是专门化,但我需要专门化至少 9 种新方法。这是我需要的示例:
我有这门课
template<typename A, typename B, typename C>
class CFoo
{
void foo()
{
// Some chunk of code depends on old A type
}
}
所以我需要检查 typeid(我听说的是 BAD)并在示例中实现这 3 个实现:
void foo()
{
if (typeid(A) == typeid(CSomeClass)
// Do this chunk of code related to A type
else
if (typeid(B) == typeid(CSomeClass)
// Do this chunk of code related to B type
else
if (typeid(C) == typeid(CSomeClass)
// Do this chunk of code related to C type
}
那么最好的解决方案是什么?我不想专门针对所有 A、B、C,因为每种类型都有 3 个专门化,所以我将获得 9 种方法或仅此 typeid 检查。
最佳答案
不好是因为
- A、B 和 C 在编译时已知,但您使用的是运行时机制。如果您调用 typeid,编译器将确保将元数据包含到目标文件中。
- 如果将“执行与 A 类型相关的这段代码”替换为使用 CSomeClass 接口(interface)的实际代码,您会发现如果 A!=CSomeClass 且 A 具有不兼容的接口(interface)。编译器仍然会尝试翻译代码,即使它从未运行过。 (见下面的例子)
您通常做的是将代码分解成单独的函数模板或可以专门化的类的静态成员函数。
差:
template<typename T>
void foo(T x) {
if (typeid(T)==typeid(int*)) {
*x = 23; // instantiation error: an int can't be dereferenced
} else {
cout << "haha\n";
}
}
int main() {
foo(42); // T=int --> instantiation error
}
更好:
template<typename T>
void foo(T x) {
cout << "haha\n";
}
void foo(int* x) {
*x = 23;
}
int main() {
foo(42); // fine, invokes foo<int>(int)
}
干杯,s
关于C++ 特化,type_of 或只是 typeid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1530579/