template class for some types: member function already defined or declared

I am having an interesting problem in C++ that goes back to declarations of functions in templated classes that become identical for certain choices of template parameters.

As a simple example, consider a templated class "Property" that shall support both cast to std::string and cast to the template type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename Type> class Property {
protected:
	Type data;

public:
	/// Implicit conversion to template type.
	operator Type() const { return data; }

	/// Implicit conversion to std::string.
	operator std::string() const { return toString(data); }
};


// VS: error C2535: 'Property<Type>::operator Type(void) const' :
// member function already defined or declared
Property<std::string> blubb;


I'm curious how to get around that issue!

For smartasses: my question was not if this is good style. It's an example demonstrating my issue.
Each function needs to have it's own template <typename Type> IIRC.
I'm curious how to get around that issue!
You can't get around that issue. If 'Type' is std::string then you have operator std::string() const twice and the compiler doesn't know which one to choose.
@firedraco the syntax is fine.

@coder777 Yeah, that's exactly the problem.

So, I was wondering, is there a way to specialize Property<std::string> to avoid that issue?


this code works fine under gcc 4.4:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template <typename Type> class Property;

template <> class Property<std::string> {
protected:
	std::string data;

public:
    Property() : data() {}
	/// Implicit conversion to template type.
	operator std::string() const { return data; }
};

template <typename Type> class Property {
protected:
	Type data;

public:
    Property() : data() {}
	/// Implicit conversion to template type.
	operator Type() const { return data; }

	operator std::string() const { return toString(data); }
};


It works thanks to the forward déclaration. In the second class template, Type means in fact everything except std::string beacause of the first specialisation.
Last edited on
Works fine under VS2010 too
closed account (1yR4jE8b)
You don't need to specialize the whole class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template <class T> class Property
{
protected:
	T data;

public:
	/// Implicit conversion to template type.
	operator T() const { return data; }
};

template <>
Property<std::string>::operator std::string() const
{
  return toString(data);
}
darkestfright, i don't think your code is what the author of the topic wants because it does not defines a string conversion for Property<T> where T is not a string.
However, aquazes solution is what I was looking for! Thank you all.

Edit: Only now I realized I have to specialize the WHOLE class. Not a beautiful solution, but a solution after all.
Last edited on
Topic archived. No new replies allowed.