简体   繁体   中英

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.

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

int main()
{
  f<decltype(10), 10>(); // will become f<int, 10>();
  return 0;
}

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.

I don't think you can do that, you simply need to let the compiler know that there is a type there. The closest thing I can think of is something like this:

template <class T>
void f(T x) {
    // do something with x
}

f(10);

Beyond that, I suppose you could just assume a bit and do something like this:

template<size_t x>
void f() {

}

f<10>();

Neither of which is quite what you want, but a decent compiler should be able to make a lot of this compile time anyway since you are passing a constant.

Can you elaborate on what you are trying to accomplish? Are non-integer types going to be allowed? Why don't you show us the more complicated template you are trying to simplify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM