Koenig's lookup for template argument.

P

Peng Yu

Hi,

I'm wondering if Koenig lookup can be applied somehow to derive which
template to use based on the template arguments.

The following code shows an example where multiply_traits's namespace
A has to be specified in the definition of Y. This makes Y unusable
for any multiply_traits defined in other namespaces, which
corresponding T1 and T2 defined in those namespaces. See also comments
in the code.

Thanks,
Peng


#include <iostream>

namespace A {

template <typename T>
class X {
public:
X() { }
X(T t) : _t(t) { }
const T &the_t() const { return _t; }
private:
T _t;
};

template <typename T1, typename T2>
struct multiply_traits;

template <typename T1, typename T2>
struct multiply_traits<X<T1>, T2> {
typedef X<T1> result_type;
};

template <typename T1, typename T2>
typename multiply_traits<X<T1>, T2>::result_type operator*(const
X<T1> &x, const T2 &t) {
return X<T1>(x.the_t() * t);
}

}

namespace B {

template <typename T>
class Y {
public:
Y(T t) : _t(t) { }
const T &the_t() const { return _t; }
private:
T _t;
};

template <typename T1, typename T2>
Y<typename A::multiply_traits<T1, T2>::result_type>
#if 0
I want to specify the template argument without explicitly say the
namespace A.
If this could be possible, Y can be used for types that are defined
in any namespace as long as a corresponding multiply_traits are
defined in such namespace.
But I just don't find such a way.
Is there anybody know if there is any walkaround?
#end if
operator*(const Y<T1> &y, const T2 &t) {
return Y<T1>(y.the_t() * t);
}
}

int main () {
A::X<int> x(2);
B::Y<A::X<int> > y(x);

std::cout << (x * 3).the_t() << std::endl;
std::cout << (y * 5).the_t().the_t() << std::endl;
}
 
D

dascandy

  template <typename T1, typename T2>
    Y<typename A::multiply_traits<T1, T2>::result_type>

IIRC, there was a proposal for "auto" return types somewhere in c++0x.
Also, boost has a template iirc that does just this - determine what
the return value of some operation is. For these concrete problems
those solutions might help you.

As for the abstract problem of template importing from an unknown
namespace, Koenig lookup doesn't apply. You need to specify the
namespace one way or another.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top