Topic: Local class member templates (once again)
Author: "Sergey S." <flex_ferrum@artberg.ru>
Date: Tue, 15 Dec 2009 11:18:42 CST Raw View
Hello.
I found the same topic was posted six years ago (http://
groups.google.com/group/comp.std.c++/browse_thread/thread/
1808df9071f684a1/b072c48bb1722f24)
Local classes already allowed to be template arguments. Why template
members are forbidden for local classes? Here is two small examples:
typedef boost::variant<int, double, char> Variant;
class SomeClass
{
public:
void ProcessVariant(Variant const& var)
{
struct Visitor : public boost::static_visitor<>
{
SomeClass const* m_outer;
Visitor(SomeClass const* cls) : m_outer(cls) {;}
template<typename T>
void operator()(T arg) const {m_outer->Process(arg);}
};
boost::apply_visitor(Visitor(this), var);
}
private:
void Process(int v) const {std::cout << "Integer: " << v <<
std::endl;}
void Process(double v) const {std::cout << "Double: " << v <<
std::endl; }
void Process(char v) const {std::cout << "Char: " << v << std::endl;}
};
Due to current draft 'Process' function should have 'public'
visibility and 'Visitor' should be external class. First can break
class interface logic ('Process' could be implementation detail) and
second is polluting enclosing namespace.
Another sample (polimorphic functors emulation):
template<typename F, typename T>
int apply_fn(F fn, T arg)
{
return fn(arg);
}
double fn1(double a)
{
return a * 2;
}
int fn1(int a)
{
return a * 10;
}
int fn2(int a)
{
return a * 3;
}
//...
class LocalClass1
{
public:
template<typename T>
T operator()(T arg) {return fn1(arg);}
};
std::cout << apply_fn(LocalClass1(), 10) << std::endl; // prints
100
std::cout << apply_fn(LocalClass1(), 10.5) << std::endl; // prints
21
std::cout << apply_fn(LocalClass2(), 10.5) << std::endl; // prints
30
//...
In this case 'LocalClass1' wraps 'fn1' call and allows to pass
oveloaded function into 'apply_fn'. Due to current draft both
'LocalClass1' and 'LocalClass2' should be outside any function
definitions.
I think there are many samples where local classes with template
members could be suitable. Why they are forbidden?
------------
Best regards,
Sergey.
--
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@netlab.cs.rpi.edu]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]