#include <iostream>
#include <vector>
class A
{
public:
int attr;
A(int a):attr(a){}
};
template <typename T>
int sum(std::vector<T> x)
{
int s = 0;
for (auto& elem : x)
{
s += elem.attr; // Problem is here, when elem is a pointer
}
return s;
}
int main()
{
std::vector<A> x1 = {1,2,3,4,5};
std::cout << "sum = " << sum(x1) << "\n";
std::vector<A*> x2;
for (auto& elem : x1)
x2.push_back(&elem);
std::cout << "sum = " << sum(x2) << "\n"; // Problem is this function call
return 0;
}
以上不会编译为 elem.attr
未定义 A*
.应该是elem->attr
.
有没有办法让这项工作无需重写整个函数sum
?
当然,sum
是一个非常小的功能,但对于更大的功能,复制粘贴长代码开始成为一个设计问题。我会很想使用 if (std::is_pointer<elem>::value)
但当然,这并不能解决问题,因为评估是在运行时而不是编译时进行的。
最佳答案
您可以使用 Constexpr If (C++17 起),在编译时工作。
If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded.
例如
if constexpr (std::is_pointer_v<T>) {
s += elem->attr; // when elem is a pointer
} else {
s += elem.attr; // when elem is not a pointer
}
关于c++ - 模板函数如何根据类型在编译时修改它的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49567104/