From: Alexandru on
i need to write a function which has the following behavior:

blah<false>(x) -> returns x.begin() // x is a containter (vector, map)
blah<true>(x) -> returns 0 // x is an integer (short, unsigned long
long)

i've been trying different combinations, but i don't know how to
specify the return type. here is one of my attempts:

template<bool V, typename T> T::const_iterator blah(const T& x)
{ return x.begin(); }
template<class T> T blah<false, T>(const T& x) { return 0; }

which gives me a compilation error. can you please help me?

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: huili80 on
On Jun 22, 5:27 pm, Alexandru <brtz...(a)gmail.com> wrote:
> i need to write a function which has the following behavior:
>
> blah<false>(x) -> returns x.begin() // x is a containter (vector, map)
> blah<true>(x) -> returns 0 // x is an integer (short, unsigned long
> long)
>
> i've been trying different combinations, but i don't know how to
> specify the return type. here is one of my attempts:
>
> template<bool V, typename T> T::const_iterator blah(const T& x)
> { return x.begin(); }
> template<class T> T blah<false, T>(const T& x) { return 0; }

You can't partically specialize a template function.

>
> which gives me a compilation error. can you please help me?

{ Edits: quoted clc++m banner removed. Another copy of the banner is available
at the end of the article, and of every clc++m article. Don't quote it. -mod }

Use a template class to help you.
--------------------------------------------------
#include <vector>

template < bool V, typename T >
struct blah_helper
{
typedef typename T::const_iterator return_type;
return_type operator()(const T& x)
{
return x.begin();
}
};

template < typename T >
struct blah_helper < false, T >
{
typedef T return_type;
return_type operator()(const T& x)
{
return 0;
}
};

template < bool V, typename T >
typename blah_helper<V,T>::return_type blah(const T& x)
{
return blah_helper<V,T>()(x);
}

int main()
{
using namespace std;

vector<int> x;
blah<true>(x);

int y;
blah<false>(y);
}


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: Oncaphillis on
Alexandru wrote:

> template<bool V, typename T> T::const_iterator blah(const T& x)
> { return x.begin(); }

You have to tell the compiler that const_iterator is a type defined
withing T via a preceding "typename".

> template<class T> T blah<false, T>(const T& x) { return 0; }
>

You can not partially specialize a function template.

HTH

O.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]