Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c++ - Code duplication between typedefs and explicit instantiations

tree.h

template<typename Functor, char Operator>
class binary_operation : public node
{
// ... unimportant details ...

    unsigned evaluate() const;
    void print(std::ostream& os) const;
};

typedef binary_operation<std::plus<unsigned>, '+'> addition;
typedef binary_operation<std::multiplies<unsigned>, '*'> multiplication;
// ...

tree.cpp

template<typename Functor, char Operator>
unsigned binary_operation<Functor, Operator>::evaluate() const
{
    // ... unimportant details ...
}

template<typename Functor, char Operator>
void binary_operation<Functor, Operator>::print(std::ostream& os) const
{
    // ... unimportant details ...
}

template class binary_operation<std::plus<unsigned>, '+'>;
template class binary_operation<std::multiplies<unsigned>, '*'>;
// ...

As you can see, there is some code duplication between the typedefs in the header file and the explicit class template instantiations in the implementation file. Is there some way to get rid of the duplication that does not require putting "everything" in the header file as usual?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is invalid and rejected by implementations because a typedef name is used in the elaborated type specifier

template class addition;

The following is invalid too, because the Standard says that there must be a simple template id contained in the elaborated type specifier. Comeau online and GCC both accept it, though.

template class addition::binary_operation;

You could apply a pervert workaround though to be fully Standards compliant

template<typename T> using alias = T;
template class alias<multiplication>::binary_operation;

At least I could not find it being invalid anymore on a quick glance over the spec.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...