2

I have the following class definition:

template <typename T>
class SeqVisitor {
public: 
    typedef string* return_type;

    return_type visit(int elem) const;
    return_type visit(char elem) const;
    return_type visit(T elem) const;
};

When I use SeqVisitor<char> a call to visit is ambiguous. If I were define the functions outside of the class definition a call to that function wouldn't be ambiguous. The compiler would choose the one with with "char elem" over "T elem". Can fix my class definition so that it will exhibit the same behavior. That is get rid of the ambiguity.

Niall C.
  • 10,878
  • 7
  • 69
  • 61
Fred Finkle
  • 1,947
  • 3
  • 18
  • 21
  • 1
    http://stackoverflow.com/questions/10579022/c-generic-function/10579338#10579338 – bobah Jun 07 '12 at 20:51
  • Are you sure you want `string *`, not just `string`? – Griwes Jun 07 '12 at 20:52
  • @bobah I'm not sure what the question/answers you are referring to, but if it's the use of two different type variables, then that wouldn't work here. I'm only looking for a way to express to use the first two methods if T=int, T=char otherwise use the third. So the types being different would work for the case where T=char, but wouldn't work in the more general case where T is something other than char or int. – Fred Finkle Jun 07 '12 at 21:57
  • There's an obvious way to do this in terms of type traits and SFINAE: just don't define visit(T elem) if type_traits::is_same is true. Are you looking for that, or something simpler? – abarnert Jun 07 '12 at 23:11
  • Yes. That's what I needed. I understood the use of traits, but I didn't make the connection to SFINAE and using it to ignore defining visit. Thanks much. – Fred Finkle Jun 08 '12 at 01:48
  • @FredFinkle I suggested that you disable generic _visit(T elem)_ for _int_ and _char_ using enable_if from _Boost_ or _static_assert()_ from _c++0x_ (both using SFINAE underneath). The link is pointing to my answer to a very similar question. Than answer contains code example. – bobah Jun 08 '12 at 12:20

2 Answers2

0

Maybe

return_type visit(char elem) const;
return_type visit(T elem, ...) const;
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

I'm sure you already know this - if you are trying to call visit() from outside your class your typedef is inside your class. Why not have the typedef somewhere outside the class if it the visit() function being called by users of the class (I'm not sure if this is what you're trying to do)

When I tried a typedef inside my class, I had problems calling the function from outside the class - but when I moved the typedef outside the class, I had no problems.

If you really are only using the typedef inside the class, what you have makes sense

A B
  • 4,068
  • 1
  • 20
  • 23