【发布时间】:2016-03-04 16:42:54
【问题描述】:
我想创建一个必须用 { } 大括号调用的函数。相似的 到 if、while 和 for 语句。这样做的原因是为了防止操作员在未添加必要代码的情况下调用该函数。
#include <iostream>
/* function to run the test */
bool runTest()
{
std::cout "PASS" << std::endl;
return true;
}
/* function will print the passed chars */
void newTest(const char *functionName, const char *testName)
{
std::cout << functionName << " " << testName;
}
int main(void)
{
/* OPTION 1 */
/* You can call it like this */
newTest("runTest", "TestName");
runTest();
/ * OR */
newTest("runTest", "TestName");
{
runTest();
}
/* OPTION 2 */
/* I want the operator to be required to do */
newTest("runTest", "TestName")
{
runTest();
}
return 0;
}
我希望选项 2 是正确的用法。因为使用选项 1,您可以这样称呼:
newTest("runTest", "TestName");
newTest("otherTest", "TestName");
runTest();
但您不会对与第一次调用输出相关的 runTest() 进行必要的调用。
输出将是:
runTests TestName /*(NULL)*/
otherTest TestName PASS
这种调用方式只是检查以确保操作员在 newTest() 函数之后调用了测试。
理想情况下,如果操作员是完美的,他可以正确调用函数。
newTest("runTest", "TestName");
runTest();
newTest("otherTest", "TestName");
runTest();
但我想消除错误,但自动要求操作员在调用后使用 {} 调用该函数。
【问题讨论】:
-
如果你想让一个函数运行用户提供的代码,你应该让你的函数接受一个函数/仿函数/lambda并在你的函数中运行它。
-
这是个好主意,我不敢相信我没有想到那个大声笑。理想情况下,这样的事情会起作用
newTest(runtests, "runTests", "TestName")
标签: c++ function macros brackets statements