Templates and void

I have a short and easy challenge: come up with a way to implement a templated function that can accept a template parameter of 'void' and use it somehow, and still be valid syntax. You may not use pointers or casting, and, to make the challenge more obvious, the function should return a const char *. Hopefully you won't have a hard time typeing it out.

EDIT: I think that I was misunderstood...scroll down for the solution or don't scroll down to try and figure it out yourself.
Last edited on
closed account (S6k9GNh0)
That does not make sense. void means nothingness. How do you have a type of nothing? What would a type of nothing consist of?
Last edited on
@Computerquip Well what if the template argument represents the type of argument to be passed to a function? You might want to signify that no argument should be passed. I imagine one would usually want to specialise this case.

@LB I'm not sure if this matches your requirements, but when I had this problem, I did the following.
 
class Void {};

Then you can do something such as thing:
1
2
3
4
5
6
7
8
9
10
11
template <class S, class T>
S* Allocate(const T& arg)
{
   return new S(arg);
}

template <class S>
S* Allocate<S, Void>(const Void& = Void())
{
   return new S();
}

A contrived example, I know, but it illustrates the point.

I'm not quite sure what you want with the whole 'return const char* const' thing. Surely the content of the templated function is not relevant. Perhaps I have missed the point.
1
2
3
4
5
template <class S> const char* const fn()
{
   // yes, I'm returning the address of a temporary. what of it? :O
   return "erm, I'm not sure what the whole 'return const char*' thing was about";
}
Last edited on
Well, since my intentional typo was misinterpreted, I'll post the solution:
1
2
3
4
5
template<typename T>
const char *Func()
{
  return(typeid(T).name());
}
Calling Func<void>() will return "void"
Last edited on
Oh, I see what you mean now. Strange, I thought you couldn't pass void to a template, but it worked this time.
Topic archived. No new replies allowed.