简体   繁体   English

用C ++中的typedef总结和定义具有两个函数的新类型

[英]typedef in C++ to summarize and define a new type with two functions

I have two function that returns a boolean value after comparing the two values that I am passing to the function. 我有两个函数,在比较我传递给该函数的两个值后返回一个布尔值。 Now by question is how can we write a typedef using the following two functions to characterize them and define a new type? 现在的问题是,我们如何使用以下两个函数编写typedef来表征它们并定义新类型?

 functions: 
    bool compare1(float n1, float n2){
      return n1<n2;
    }

    bool compare2(int n1, int n2){
      return n1<n2;
    }

I don't see a typedef doing much good here, but a template certainly could: 我看不到typedef在这里做得很好,但是模板当然可以:

template <class T>
bool compare(T n1, T n2) { 
   return n1 < n2;
}

Note that this is pretty much the same as std::less<T> already provides, except that std::less<T> has specializations so it works with some types for which n1<n2 wouldn't necessarily give meaningful results. 请注意,这与std::less<T>已经提供的功能几乎相同,只是std::less<T>具有特殊化,因此它可以与某些类型的n1<n2不一定给出有意义的结果一起使用。 That means this exact case isn't very practical, but other cases of the general idea can be. 这意味着这种确切的情况不是很实用,但是一般想法的其他情况也可以。

For the original case, you can't really use a typedef . 对于原始情况,您不能真正使用typedef You can create a typedef for the type of a pointer to one of the functions: 您可以为函数之一的指针类型创建一个typedef

typedef bool (*ptr_func)(int, int);

But that still needs the parameter types specified, so you can't use it to refer to both functions that takes int parameters and functions that take float parameters. 但这仍然需要指定的参数类型,因此您不能使用它来同时引用带有int参数的函数和float参数的函数。 You can create a typedef for a pointer to a function that takes a variadic argument list, but even though such a function could take either int or float parameters, that pointer wouldn't be the right type to refer to either of the functions you've given. 您可以为带有可变参数列表的函数的指针创建typedef ,但是即使这样的函数可以采用intfloat参数,该指针也不是引用您所使用的函数的正确类型。给出。

If you really really want to have an alias (aka typedef ), then here it is: 如果您真的想要一个别名 (又名typedef ),那么这里是:

bool compare1(float n1, float n2){
  return n1<n2;
}

bool compare2(int n1, int n2){
  return n1<n2;
}

template <typename T>
using Alias = bool(*)(T,T);

int main()
{    
    Alias<float> a = compare1;
    std::cout << a(3.14f, 5.12f) << std::endl;

    Alias<int> b = compare2;
    std::cout << b(1, 2) << std::endl;
}

LIVE DEMO 现场演示

Probably you want to do something like this: 可能您想执行以下操作:

template<typename T>
bool compare(T n1, T n2){
  return n1 < n2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM