Template parameters for template function

R

rush.william

Hello All!

There is following code:

template < class T >
void f(T const & value)
{
};

Is there any way to force user to specify template parameters
explicitly? I want to do the following:
f<int>(1); // Normal
f(1); // This should give an error

Any ideas?...

WBR
 
G

Gianni Mariani

Hello All!

There is following code:

template < class T >
void f(T const & value)
{
};

Is there any way to force user to specify template parameters
explicitly? I want to do the following:
f<int>(1); // Normal
f(1); // This should give an error

Any ideas?...


Try this:


template < class T >
struct f_helper
{
typedef T type;
};


template < class T >
void f(typename f_helper<T>::type const & value)
{
};

The compiler is unable to deduce the type T from f_helper<T>::type.
 
M

Markus Moll

Hi

Is there any way to force user to specify template parameters
explicitly? I want to do the following:
f<int>(1); // Normal
f(1); // This should give an error

Any ideas?...

You would have to make T undeducible. (word sounds wrong?)
You could for example use an indirection:

template<typename T>
struct f_helper
{
const T& value;
f_helper(const T& value) : value(value) {}
operator const T& () const { return value; }
};

template<typename T>
void f(const f_helper<T>& h)
{
const T& value = h;
// ...
}

Then f(1) fails to compile, while f<int>(1) will still compile.

Markus
 
G

Gleb Golubitsky

Gianni Mariani:
Try this:


template < class T >
struct f_helper
{
typedef T type;
};


template < class T >
void f(typename f_helper<T>::type const & value)
{
};

The compiler is unable to deduce the type T from f_helper<T>::type.

Thanks, it works!...
 
P

Pete Becker

Markus said:
You would have to make T undeducible. (word sounds wrong?)

The standard doesn't use the word "deducible," so there's no direct help
there. But it does use the word "deduced" as in "deduced context", and
it uses the word "non-deduced" as its opposite.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top