Reputation: 93
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.
Upvotes: 9
Views: 929
Reputation: 15154
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.
Upvotes: 5
Reputation: 90422
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.
Upvotes: 2
Reputation: 3052
C++0x introduces decltype()
, which does exactly what you want.
int main()
{
f<decltype(10), 10>(); // will become f<int, 10>();
return 0;
}
Upvotes: 5