有没有办法在 C++ 中使用逻辑操作作为模板?
Is there a way to use logical operations as templates in C++?
例如,我想控制 A
和 B
之间的运算符,具体取决于我分配给它的模板(在 main
中)。
// Theoretical operation template function
template <OPERATION>
void Example(int A, int B) {
A OPERATION B;
}
int main(void) {
Example< += >(10, 20);
Example< -= >(10, 20);
Example< *= >(10, 20);
Example< |= >(10, 20);
}
我知道这不是有效的 C++ 语法,但我这样做只是为了解释。这可能吗?提前致谢。
您可以在操作上模板 Example
,并将操作作为第三个参数传递。传递操作的一种简单方法是作为 lambda,或者如@Yksisarvinen 上面评论的那样,作为 std::functional
.
中可用的函数 objects 之一
下面的示例使用算术运算符而不是逻辑运算符(您似乎想在问题标题中使用逻辑运算符,但在您的示例中使用算术运算符)。
#include <functional> // plus, minus, multiplies, divides
#include <iostream> // cout
template <typename Op>
void Example(int a, int b, Op&& op) {
std::cout << "result = " << op(a, b) << "\n";
}
int main(void) {
Example(10, 20, std::plus<int>{});
Example(10, 20, std::minus<int>{});
Example(10, 20, [](int a, int b) { return a * b; }); // or multiplies
Example(10, 20, [](int a, int b) { return a / b; }); // or divides
}
// Outputs:
//
// result = 30
// result = -10
// result = 200
// result = 0
例如,我想控制 A
和 B
之间的运算符,具体取决于我分配给它的模板(在 main
中)。
// Theoretical operation template function
template <OPERATION>
void Example(int A, int B) {
A OPERATION B;
}
int main(void) {
Example< += >(10, 20);
Example< -= >(10, 20);
Example< *= >(10, 20);
Example< |= >(10, 20);
}
我知道这不是有效的 C++ 语法,但我这样做只是为了解释。这可能吗?提前致谢。
您可以在操作上模板 Example
,并将操作作为第三个参数传递。传递操作的一种简单方法是作为 lambda,或者如@Yksisarvinen 上面评论的那样,作为 std::functional
.
下面的示例使用算术运算符而不是逻辑运算符(您似乎想在问题标题中使用逻辑运算符,但在您的示例中使用算术运算符)。
#include <functional> // plus, minus, multiplies, divides
#include <iostream> // cout
template <typename Op>
void Example(int a, int b, Op&& op) {
std::cout << "result = " << op(a, b) << "\n";
}
int main(void) {
Example(10, 20, std::plus<int>{});
Example(10, 20, std::minus<int>{});
Example(10, 20, [](int a, int b) { return a * b; }); // or multiplies
Example(10, 20, [](int a, int b) { return a / b; }); // or divides
}
// Outputs:
//
// result = 30
// result = -10
// result = 200
// result = 0