In a C++ template with the generic type T, I can use
const T &
to get a reference to a constant T. However, if now T itself is a reference type (like e.g. T = int &), the above term resolves to
int &
and not to
const int &
which quite makes sense, since any reference itself is always constant. However, is there still a way to require a
const T &
if T itself is a reference type?
Edit: sample code to evaluate (g++ compiler):
template <typename T> class TemplateClass
{
public:
void foo(const T &bar) { }
};
int main()
{
TemplateClass<int &> x;
x.foo(0); // <-- compile error: no conversion from int to int&
return 0;
}
You can always use template specialisation to implement a different version for any kind of reference:
Now,
X<int>::foo
expects anint const&
andX<int&>::foo
expects anint const&
, too.However, it is not entirely clear from your question what you are trying to do exactly.
Edit: My g++ version (4.6.1) does not complain without template specialisation for the following
While it does for
Which is correct IMO, because you try to convert a temporary (
7
) to a mutable reference (even if that is a reference to a const reference).Edit 2: If you want to reduce duplicate code, then do not specialise your original class, but use this:
I have encountered the very same problem. It seems that the '&' type conversion operator binds stronger than the 'const' qualifier. So when we have this code:
the function ends up with type void(int&), not the expected void(const int&).
To solve this problem, I have defined this template:
Now define your function as:
The instantiated function will have the type void(const int&), as needed.
Remove the reference:
Now it works as expected.