Cannot dereference variable in a set...

Hello everybody, will be grateful is somebody can help!

I get errors C2100 (illegal indirection) and C2088 ("<<": illegal for class) while trying to use the myPrint function (irrespectively of whether the set for printing contains pointers or not):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <class T = std::string>
void myPrint(const std::set<T>& mySet)
{
	std::cout << "Size of vector is " << mySet.size() << ", Pointers: ";
	bool pp = false; std::string str = "no";
        if (std::is_pointer<T>::value) { pp = true; str = "yes"; }

	std::cout << pp << "\n[";
	std::set<T>::const_iterator i;
	for (i = mySet.begin(); i != mySet.end(); ++i)
	{
		if (pp) { std::cout << *(*i) << ","; }
		else { std::cout << *i << ","; }
	}
	std::cout << "]\n";
}

The errors point to the line "if (pp) { std::cout << *(*i) << ","; }", but I cannot figure out what's wrong with it... Anybody knows how to solve this problem?
You have a a vector of type T, where t is an std::string, why are you trying to deference an std::string?
This is the default type (i.e. if I will call myPrint<>(x) then x should be set of strings), but generally T can be any: double*, int, char* etc. (e.g. for myPrint<double>(x) the set x should obviously consist from double).
> I cannot figure out what's wrong with it...

if(pp) is evaluated at run time.
std::cout << *(*i) << ","; is parsed at compile time.

Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <set>
#include <type_traits>

template < typename T >
typename std::enable_if< std::is_pointer<T>::value >::type
my_print( const std::set<T>& set )
{
    std::cout << "size: " << set.size() << ", contains pointers [ " ;
	for( auto i = set.begin() ; i != set.end(); ++i )
	    if( *i ) std::cout << **i << ' ' ;
        else std::cout << "null " ;
	std::cout << "]\n";
}

template < typename T >
typename std::enable_if< !std::is_pointer<T>::value >::type
my_print( const std::set<T>& set )
{
	std::cout << "size: " << set.size() << ", contains values [ " ;
	for( auto i = set.begin() ; i != set.end(); ++i ) std::cout << *i << ' ' ;
	std::cout << "]\n";
}

int main()
{
    const std::set<std::string> set_of_values { "one", "two", "three" } ;
    my_print(set_of_values) ;

    std::set< const std::string* > set_of_pointers ;
    for( const auto& str : set_of_values ) set_of_pointers.insert( std::addressof(str) ) ;
    my_print(set_of_pointers) ;
}

http://coliru.stacked-crooked.com/a/cbadbbb77e32ad72
Great!!! Thank you, works like a charm!
Topic archived. No new replies allowed.