在main()之前调用void函数 [英] Calling void function before main()
问题描述
我想知道是否可以使用temp变量不调用void函数.例如.在以下代码块中...
I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block...
#include <iostream>
void earlyInit()
{
std::cout << "The void before the world." << std::endl;
}
int g_foo = (earlyInit(), 0);
int main( int argc, char* argv[] )
{
std::cout << "Hello, world!" << std::endl;
}
...我不需要g_foo
,宁愿它不存在.有没有一种方法可以在没有中间临时变量的情况下调用void函数?
...I have no need for g_foo
and would rather it not exist. Is there a way to call void functions without an intermediate temp variable?
推荐答案
我想知道是否可以在不使用temp变量的情况下调用void函数.例如.在下面的代码块中.
I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block.
该语言不提供任何此类机制.正如其他答案所指出的那样,可能存在特定于编译器的方法.
The language does not provide any such mechanism. As other answers have pointed out, there maybe compiler-specific ways to do that.
但是,我认为您的方法没有任何问题.我经常使用以下模式.
However, I don't see anything wrong with your approach. I use the following pattern a lot.
#include <iostream>
namespace mainNS // A file-specific namespace.
{
void earlyInit()
{
std::cout << "The void before the world." << std::endl;
}
struct Initializer
{
Initializer();
};
}
using namespace mainNS;
static Initializer initializer;
Initializer::Initializer()
{
earlyInit();
// Call any other functions that makes sense for your application.
}
int main( int argc, char* argv[] )
{
std::cout << "Hello, world!" << std::endl;
}
这篇关于在main()之前调用void函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!