fay*_*aya 2 c++ types specialization
我想知道在我的情况下使用什么更好以及为什么.首先,我听说使用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
}
}
Run Code Online (Sandbox Code Playgroud)
所以我需要更确切地检查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
}
Run Code Online (Sandbox Code Playgroud)
那么什么是最好的解决方案?我不想专注于所有A,B,C,因为每种类型都有3个特化,所以我将得到9个方法或只是这个类型检查.
这很糟糕,因为
您通常所做的是将代码分解为单独的函数模板或可以专用的类的静态成员函数.
坏:
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
}
Run Code Online (Sandbox Code Playgroud)
更好:
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)
}
Run Code Online (Sandbox Code Playgroud)
干杯,s
| 归档时间: |
|
| 查看次数: |
4405 次 |
| 最近记录: |