0

Note, I'm aware of this question, but what I want is different.

My current code (the sum total of my main.cpp) looks like this standard boilerplate for making a class into an executable:

#include <MyHeader.h>
int main(int argc, char **argv)
{
    return MyTemplate<MyClass>(argc, argv);
}

This works quite happily, but it would be even better if I could do just:

#include <MyMainWrapper.h>
// UPDATE: commented out... MyMainWrapper<MyTemplate, MyClass> main;
MyMainWrapper<MyTemplate, MyClass> someObjectThatGeneratesMain;

And that would expand to the code above. It could of course be easily done with a macro, but I'm interested to see if there is a template solution, or if not, why not?

UPDATE: I imagine a function template that might somehow do:

template<...>
extern "C" int main(int argc, char **argv)
{
   //...
}

But I see that templates cannot be extern "C".

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • I can't fathom why you'd want a stick all code into a single class. Be as it may, I don't understand what the last block is supposed to mean, you declared something called `main` and it is clearly not a function definition, feels like a dupe to me. – Passer By Oct 06 '17 at 05:12
  • @PasserBy There's a good number of other classes hidden behind the `MyClass`, which can be either instantiated from `main()` for stand-alone operation as seem here, or used in a shared library form, which has a different template+macro definition method. I separate things out so I can build the core library once, then link multiple times with the shared library form and multiple mains. – Ken Y-N Oct 06 '17 at 06:20
  • 1
    You can declare the class and an empty `main`, example: `MyMainWrapper foo; int main(){};` the constructor for `MyMainWrapper` will be called. You still need an entry point. `main` doesn't have to do anything but it has to be there, or some other entry point. – Barmak Shemirani Oct 06 '17 at 06:31
  • Good idea, but I actually need the `argc` and `argv` inside my template. – Ken Y-N Oct 06 '17 at 06:35
  • In Windows you can use `GetCommandLine` (and the optional `CommandLineToArgv`) outside of `main`. I don't know how it would be done in other operating systems. – Barmak Shemirani Oct 06 '17 at 06:55

1 Answers1

1

There is no template solution, because main is a pure C interface.

With all the decoration added for template specializations, the linker has no chance of knowing what exactly is supposed to be your "main".

#include <MyMainWrapper.h>
MyMainWrapper<MyTemplate, MyClass> main;

This isn't a function either, so it won't match the required signature. It may be a callable, but that is syntactic sugar added by C++ and doesn't link.

Ext3h
  • 5,713
  • 17
  • 43
  • OK, I've tried to expand what I'm asking for - using the name `main` there is confusing, I agree. (It seems impossible, now I spell it out more explicitly!) – Ken Y-N Oct 06 '17 at 06:28