2

I have a doubt about if that approach is possible, lets say you want two ways of calling a function at same time, one is returning an object and the other return by reference in parameter:

// ... template <class T> void func(Foo<T>& f, const T n) { f.a = Something(f.a + n); f.b = Something(f.b + n); } template <class T> Foo<T> func(const Foo<T>& f, const T n) { return Foo<T>( Something(f.a + n), Something(f.b + n) ); } // ... // main Foo<int> foo(1, 1); func(foo, 2); Foo<int> foo2 = func(foo, 2); 

The const word in first parameter affect the signature of method?

1
  • I don't think you can do it taht way Commented Feb 28, 2012 at 15:06

2 Answers 2

5

Yes it does. const affects the signature, the return type does not.

1.3.11 signature

the information about a function that participates in overload resolution (13.3): its parameter-type-list (8.3.5) and, if the function is a class member, the cv-qualifiers (if any) on the function itself and the class in which the member function is declared. [...]

const is part of hte parameter-type-list, so it does determine an overload.

Sign up to request clarification or add additional context in comments.

Comments

3

Yes, a reference to const is a separate type to a reference to non-const, so the two functions with these arguments are separate overloads.

However, this will not work:

Foo<int> foo2 = func(foo, 2); 

Since foo is not const, this will select the non-const overload, which has no return value; so the assignment will fail. You would need to explicitly choose the const version:

Foo<int> foo2 = func(static_cast<const Foo<T>&>(foo), 2); 

2 Comments

Why not use const_cast instead?
@JoachimPileborg: Because const_cast is a more dangerous cast than is needed; in this case, it could remove a volatile qualifier. (Although static_cast could perform an unsafe type conversion; unfortunately, there's no explicit cast that only allows standard conversions).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.