Re: How do I initialize const int with int?
* DeMarcus:
Hi!
I'm stuck in a template. Can anyone see what I'm doing wrong?
template<typename T>
class Foo
{
public:
Foo( T t ) {}
};
class Bar
{
public:
template<typename T>
void add( Foo<T>& foo, T t ) {}
};
int main()
{
Foo<const int> foo( 47 );
Bar b;
b.add( foo, 11 ); // ERROR!
// "No matching function for call to Bar::add(Foo<const int>&, int)"
}
I want the function be Bar::add(Foo<const int>&, const int)
How can I achieve that?
Background: a top level const for a formal argument is not part of the routine's
signature. The matching rules are complicated and I won't pretend to understand
what exactly is going on (sitting down with the Holy Standard would presumably
clarify that in just a matter of half an hour or so, but with no practical
significance). But I very much suspect that it's that top-level const rule.
First I simply tried ...
template< typename T >
void add( Foo<T>& foo, T const& t ) {}
.... but that didn't work (I guess James Kanze can explain why), so then I did:
<code>
template<typename T>
class Foo
{
public:
Foo( T ) {}
};
class Bar
{
private:
template<typename T>
void do_add( Foo<T>&, T ) {}
public:
template<typename T>
void add( Foo<T const>& foo, T t ) { do_add<T const>( foo, t ); }
template<typename T>
void add( Foo<T>& foo, T t ) { do_add<T>( foo, t ); }
};
int main()
{
Foo<int const> foo( 47 );
Foo<int> foo2( 123 );
Bar b;
b.add( foo, 11 );
b.add( foo2, 12 );
}
</code>
Cheers & hth.,
- Alf