所以给定一个函数 f 有没有办法为某些单独的不相关的类定义特定的行为,没有一些宏 foo
例如替换/完成相同事情的方式:
//p for param
template<typename T>
T f(T p){ // some default op};
template<>
T f<float>(T p)
{ return 2*p; }
template<>
T f<double>(T p)
{ return 2*p; }
template<>
T f<int>(T p)
{ return 2*p; }
template<>
T f<std::string>(T p)
{ //return p copies of the string appended together; }
template<>
T f<std::vector>(T p)
{ //return the vector's element's copied}
// etc
不,我不喜欢正常的过载。理想情况下类似于模板
if T in [int, float, double]
T f(T p) { return 2*p; }
else // 定义默认的其他行为。你可以在 python 中做到这一点。
无论如何要根据T的类别做出决定?我能想到的一个可能的解决方案是非常......不漂亮的是使用 typeid 和 demangling。
假设由于某种原因你有一个超泛型函数和大约 15 个不同的类,写出所有使用重载都不是很好。