考虑下面的示例代码。
#include <iostream>
enum class FruitType {
APPLE,
ORANGE
};
class Fruit {
uint64_t apple_count;
uint64_t orange_count;
public:
Fruit() : apple_count(0), orange_count(0) {}
void increase_count(FruitType type) {
if (type == FruitType::APPLE)
apple_count++;
else
orange_count++;
}
void print() {
std::cout << "apple_count: " << apple_count << std::endl;
std::cout << "orange_count: " << orange_count << std::endl;
}
};
int main(int, char**) {
Fruit fruit;
fruit.increase_count(FruitType::APPLE);
fruit.increase_count(FruitType::ORANGE);
fruit.increase_count(FruitType::APPLE);
fruit.increase_count(FruitType::APPLE);
fruit.increase_count(FruitType::ORANGE);
fruit.print();
return 0;
}
我希望 increase_count
函数有效地编译为 increase_count_apple
和 increase_count_orange
。这是另一个类的简化示例,理论上,这种编译时优化在运行时对我有帮助。直观上,这感觉可以使用模板,但我无法获得令人满意的输出。
最佳答案
通过制作increase_count
一个采用非类型模板参数的模板,您可以这样做
class Fruit {
uint64_t apple_count;
uint64_t orange_count;
public:
Fruit() : apple_count(0), orange_count(0) {}
template <FruitType type>
void increase_count() {
if constexpr (type == FruitType::APPLE)
apple_count++;
else
orange_count++;
}
void print() {
std::cout << "apple_count: " << apple_count << std::endl;
std::cout << "orange_count: " << orange_count << std::endl;
}
};
int main(int, char**) {
Fruit fruit;
fruit.increase_count<FruitType::APPLE>();
fruit.increase_count<FruitType::ORANGE>();
fruit.increase_count<FruitType::APPLE>();
fruit.increase_count<FruitType::APPLE>();
fruit.increase_count<FruitType::ORANGE>();
fruit.print();
return 0;
}
它会在编译时删除分支并 fruit.increase_count<FruitType::APPLE>
有效调用 increase_count_apple
和fruit.increase_count<FruitType::ORANGE>()
来电 increase_count_orange
.
关于c++ - 如何使用模板选择类(class)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76406626/