Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template non-type parameter type deduction

I'am trying to do this work:

template < typename T, T VALUE >
void            f()
{
    /* ... */
}

int             main()
{
    f<10>();    // implicit deduction of [ T = int ] ??
    return (0);
}

The purpose is to simplify a much more complex template.

After many searches, I don't find any way to do that on C++0x, so stackoverflow is my last resort.

  • without specify all type of T possible...
  • I am on g++ C++0x, so sexy stuff is allowed.
like image 950
Gravemind Avatar asked Feb 03 '23 16:02

Gravemind


2 Answers

C++0x introduces decltype(), which does exactly what you want.

int main()
{
  f<decltype(10), 10>(); // will become f<int, 10>();
  return 0;
}
like image 89
Sean Avatar answered Feb 11 '23 11:02

Sean


There is no automatic template deduction for structs/classes in C++. What you can do though is something like this (warning, untested!):

#define F(value) f<decltype(value), value>

template < typename T, T VALUE >
void            f()
{
    /* ... */
}

int             main()
{
    F(10)();
    return (0);
}

It is not as clean as template only code but it's clear what it does and allows you to avoid the burden of repeating yourself. If you need it to work on non-C++0x compilers, you can use Boost.Typeof instead of decltype.

like image 28
Karel Petranek Avatar answered Feb 11 '23 12:02

Karel Petranek