[英]C++ Template class/type to choose between max and min
I am trying to write a templated class. 我正在尝试编写一个模板化的类。
template <<typename T>>
myclass {
// ...
}
I want T
to be such that if I instantiate myclass obj<T>
with a proper T
, the class should be able to choose between min or max of two numbers. 我希望
T
成为这样,如果我使用适当的T
实例化myclass obj<T>
,则该类应该能够在两个数字的最小值或最大值之间进行选择。 ie myclass is instantiated with min or max as the case maybe. 即myclass可能用min或max实例化。
I dont mind using std::less/std::more/std::max/std::min or any of the inbuilt functor objects. 我不介意使用std :: less / std :: more / std :: max / std :: min或任何内置仿函数对象。
However, I would prefer not to use enums in the constructor and then depending on the enum value, call min or max routines. 但是,我不想在构造函数中使用枚举,然后根据枚举值调用min或max例程。 I want the code to be a little cleaner.
我希望代码更加简洁。 Any ideas?
有任何想法吗? Is it possible to do this at all in C++
是否可以在C ++中完全做到这一点
This isn't a big deal. 这没什么大不了的。 Consider the following:
考虑以下:
template<typename T> class MyClass {
public:
int foo(int a, int b) const {
return T()(a, b);
}
};
Now if T
is a type whose operator()
returns the maximum of it's two arguments, then you will return the maximum, and ditto for any other binary algorithm you wish to apply. 现在,如果
T
是其operator()
返回其两个参数中最大值的类型,则您将返回最大值,并且对要应用的任何其他二进制算法也是如此。
[EDIT] I believe that I didn't fully get the point of your question and that @DeadMG's answer is in fact what you are looking for. [编辑]我相信我还没有完全理解您的问题,@ DeadMG的答案实际上就是您想要的。
The template below allows you to instantiate a class which given T, MIN, MAX can provide some number X between MIN and MAX between T. 下面的模板允许您实例化一个类,该类在给定T,MIN,MAX的情况下可以提供MIN和MAX之间的一些数字X。
template<int T, int MIN, int MAX, int X = MIN + T/(MAX - MIN)>
class MyClass
{
int foo() const
{
return X;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.