Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ > function templa...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 5 Topic 43770 of 47563
Post > Topic >>

function template specialization

by aaragon <alejandro.aragon@[EMAIL PROTECTED] > Mar 9, 2008 at 05:13 PM

Hi... after trying several things with some templated code I decided
to ask the experts a couple of things. I have the following class
template:

template<class A>
class Expr {
    A a_;
    public:
  ... // some public functions
  ...
    friend inline std::ostream& operator<<(std::ostream& os, const
Expr<A>& e) {
        os<<e.a_();
        return os;
    }
};

operator<< works just fine, but then I wanted to have the operator<<
with different behaviors depending on the template parameter. So, I
tried the following inside the class:
    // declaration inside the class
    friend std::ostream& operator<<<A>(std::ostream& os, const Expr&
e);

and defining the function outside:
    template <class A>
    inline std::ostream& operator<<(std::ostream& os, const Expr<A>&
e) {
        os<<e();
        return os;
    }

Then I got just too many errors because of ambiguous calls and others
like:
cppblas.hpp:862: error: template-id 'operator<< <UnOp<Vector<double>,
TrOp> >' for 'std::basic_ostream<char, std::char_traits<char> >&
operator<<(std::basic_ostream<char, std::char_traits<char> >&, const
Expr<UnOp<Vector<double>, TrOp> >&)' does not match any template
declaration

So then, I decided to forward the function call to another function,
say print:

template <class A>
inline std::ostream& print(std::ostream& os, const Expr<A>& e) {
	os<<e();
	return os;
}

so this also works fine, and now I can specialize the function for
specific class of A:

template <>
inline std::ostream& print<someClass>(std::ostream& os, const
Expr<someClass>& e) {
	// partially specialized for someClass
	return os;
}

Now the questions is, is this the better way to do this? Forwarding a
function call seems right, but probably it can be done without another
function. I tried hard overloading operator<< but no success. Any
hints??

Thank you all...

a=B2
 




 5 Posts in Topic:
function template specialization
aaragon <alejandro.ara  2008-03-09 17:13:42 
Re: function template specialization
Ian Collins <ian-news@  2008-03-10 13:38:41 
Re: function template specialization
aaragon <alejandro.ara  2008-03-09 18:28:16 
Re: function template specialization
James Kanze <james.kan  2008-03-10 11:39:24 
Re: function template specialization
aaragon <alejandro.ara  2008-03-16 14:52:05 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Sun Sep 7 8:18:18 CDT 2008.