Re: Does C++ support type deduction from inner class of a template?
On 19 Feb., 02:27, Jesse Perla <jessepe...@gmail.com> wrote:
I can't get the compiler to deduce the type in a template function
when being passed an inner class. Any ideas? If I remove the
template from the class, everything works fine...
Here is a minimalist example (in reality I am actually trying to
overload << for streams).
template<std::size_t N>
class simplex
{
public:
class simplex_results{
};
simplex_results res() const{return res_;}
protected:
simplex_results res_;
};
template<std::size_t N>
void f (const typename simplex<N>::simplex_results& res)
{
};
int main()
{
simplex<2> opt;
simplex<2>::simplex_results res = opt.res();
f<2>(res); //works
// f(res); //Fails to compile
}
It is not possible (in general) to deduce any template
parameter from a template based on some member
type. There are at least two reasons for that:
1) Consider a template like the following one
template <std::size_t N>
struct simplex {
typedef int simplex_results;
};
deduced in
template<std::size_t N>
void f (const typename simplex<N>::simplex_results&);
int main() {
simplex<42>::simplex_results sr = 0;
f(sr);
}
The compiler is able to see that you provided an int
to f, but how should the compiler deduce from
this information the value N == 42?
2) Templates allow specializations. Consider your
original example simplified:
template<std::size_t N>
class simplex
{
public:
class simplex_results{};
};
template<>
class simplex<13>
{
public:
typedef simplex<2>::simplex_results simplex_results;
};
template<>
class simplex<5>
{
public:
typedef bool simplex_results;
};
These example should clearly demonstrate that
no strict correlation starting from
template<Args>::some_name
and searching *to*
Args
exists (only vice versa).
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]