简体   繁体   English

我如何将定义(#define SOME_DEFINE)作为函数的参数传递?

[英]How can i pass define (#define SOME_DEFINE) as parameter of the function?

Well, I was experimented with language features, and didn't find the way, how can I pass define to the function as param.好吧,我尝试了语言功能,但没有找到方法,如何将定义作为参数传递给函数。 I know, that it's not the best practice, just pure interest.我知道,这不是最佳实践,只是纯粹的兴趣。

I've already tried to do it in several ways, at least generics didn't help.我已经尝试以多种方式做到这一点,至少泛型没有帮助。

So, what I'd like to do is:所以,我想做的是:

#define SOME_DEFINE

template <class T>
void foo(T param)
{
    if(param == SOME_DEFINE) do stuff
}

int main
{
    foo(SOME_DEFINE);
}

Appreciate you.感谢你。

All that's missing is a value to your definition.所缺少的只是您的定义的一个值。

Just add it and you can start testing the feature.只需添加它,您就可以开始测试该功能。

#include <iostream>

#define SOME_DEFINE 42

void do_all_the_things() {
  std::cout << "woohoo!" << std::endl;
}

void do_none_of_the_things() {
  std::cout << "darn" << std::endl;
}

template <class T>
void foo(T param) {
  if (param == SOME_DEFINE) {
    do_all_the_things();
  } else {
    do_none_of_the_things();
  }
}

int main() {
  foo(42);
  foo(3);
  return 0;
}

For strings, it gets a tad bit more complicated.对于字符串,它变得有点复杂。 String literals, const char* can't be compared very easily.字符串文字, const char*不能很容易地进行比较。 For example:例如:

const char* a = "value a";
const char* b = "value b";
return a == b;

May seem like it works, but it's actually just comparing the pointers and not the content.可能看起来它有效,但它实际上只是比较指针而不是内容。 You could fix this by either defining your macro as std::string("an example value") or using a specialized compare function.您可以通过将宏定义为std::string("an example value")或使用专门的比较函数来解决此问题。

#include <iostream>
#include <cstring>

#define SOME_DEFINE "test value"

void do_all_the_things() {
  std::cout << "woohoo!" << std::endl;
}

void do_none_of_the_things() {
  std::cout << "dang it" << std::endl;
}

template <class T>
struct AreEqual final {
  bool operator () (T a, T b) const {
    return a == b;
  }
};

template <>
struct AreEqual<const char*> final {
  bool operator () (const char* a, const char* b) const {
    return std::strcmp(a, b) == 0;
  }
};

template <class T, class AreEqualTo = AreEqual<T>>
void foo(T param, AreEqualTo are_equal_to = AreEqualTo()) {
  if (are_equal_to(param, SOME_DEFINE)) {
    do_all_the_things();
  } else {
    do_none_of_the_things();
  }
}

int main() {
  foo("test");
  foo("test value");
  return 0;
}

This is another worthy route to explore if you're learning the language.如果您正在学习该语言,这是另一条值得探索的途径。 There are a lot of functions in the C++ library that use template functions. C++ 库中有很多使用模板函数的函数。

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

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