tags:

views:

211

answers:

6

Inside a C++ template function foo(), a call to ::bar(TT*) gives the following error under gcc 4.4.3:

g++ -o hello.o -c -g hello.cpp
hello.cpp: In function 'void foo(std::vector<TT*, std::allocator<TT*> >&)':
hello.cpp:8: error: '::bar' has not been declared

Here's the offending code:

// hello.cpp

#include <vector>

template<typename TT> void foo(std::vector<TT*> &vec)
{
    TT *tt;
    ::bar(tt);
    vec.push_back(tt);
}

class Blah
{
};

void bar(Blah *&)
{
}

int main(int argc, char *argv[])
{
    std::vector<Blah*> vec;
    foo(vec);

    return 0;
}

C++ distinguishes between symbols that are dependent on the template parameter (TT, here) and those symbols that are independent and can be evaluated immediately.

Clearly, the compiler thinks my ::bar(TT*) call is independent and tries to resolve it immediately. Just as clearly, that function call is dependent on TT because the function call takes a parameter of type TT*, so the compiler should wait until the foo(vec) instantiation to resolve ::bar(TT*).

Is this a gcc bug or am I missing something subtle about C++ templates?

EDIT: here's a slightly more complicated example with two versions of ::bar() to clarify that declaration order is not the issue with my problem. When parsing the template, the compiler has no way of knowing if main() down below is going to instantiate the template function with TT=Blah or with TT=Argh. Therefore the compiler should not be giving an error until line 35 line 28 at the earliest (if ever). But the error is given for line 8 line 16.

EDIT #2: improved this example.

EDIT #3: added corrections to this example to make it work as desired. The bar(tt) now correctly refers to bar(Blah*). Rationale given below. (Thanks everyone).

// hello.cpp
#include <vector>

class XX {};
void bar(XX*) {}

class CC {
public:
    void bar();
    void bar(int *);
    void bar(float *);

    template<typename TT> static void foo(std::vector<TT*> &vec);
};

template<typename TT>
void CC::foo(std::vector<TT*> &vec) {
    using ::bar;
    TT *tt;
    bar(tt);
    vec.push_back(tt);
}

class Argh {};
void bar(Argh *&aa) { aa = new Argh; }

class Blah {};
void bar(Blah *&bb) { bb = new Blah; }

int main(int argc, char *argv[]) {
    std::vector<Blah*> vec;
    CC::foo(vec);
    return 0;
}
+1  A: 

This should work, your problem is the declaration order:

// hello.cpp

#include <vector>


class Blah
{
public:

};

void bar(Blah *&)
{ }

template<typename TT> void foo(std::vector<TT*> &vec)
{
    TT *tt;
    ::bar(tt);
    vec.push_back(tt);
}


int main(int argc, char *argv[])
{
    std::vector<Blah*> vec;
    foo(vec);

    return 0;
}
Tarantula
DeadMG
No this answer is incorrect. There could be many versions of bar() taking different types of pointers for their one parameter. Some of them haven't even been invented yet. That's the whole point of having a template involved.
Shawn Yarbrough
But there aren't many versions of bar(). There's just one. Why have a templated function call a non-templated function with a template-type-dependent argument? You're just limiting the range of template arguments to those accepted by the non-templated function, defying their purpose.
DeadMG
Have you tried to compile it ? I still can't understand what is your problem.
Tarantula
@DeadMG: I think you're missing the point. The question is not about "many versions" of `bar`, it's about why `bar` needs to be defined before the template even though the template is not instantiated until `main`.
casablanca
@casablanca: It doesn't need to be defined, it needs to be declared. The compiler is supposed to (under the rules of the Standard) determine whether `::bar` is a true function or function object and this happens while parsing the template, not at the point of instantiation.
Ben Voigt
@Ben, do you have a location in the Standard describing that?
Shawn Yarbrough
@Ben: See my answer, if that were the reason, any one overload should do, but gcc insists on having the exact signature. Anyhow, it seems Chris Dodd's answer pretty much explains it.
casablanca
@Shawn: It's 14.6.3 `[temp.nondep]` in the C++0x FCD.
Ben Voigt
A: 

Your code works fine on VS2005. so it indeed seems like a bug in gcc. (I don't know what the specs say about this, maybe someone will come along and post it.)

As for gcc, I also tried defining a different overload of bar before foo, so that the symbol bar is at least defined:

void bar(float *) {
}

template<typename TT> void foo(std::vector<TT*> &vec)
{
    TT *tt;
    ::bar(tt);
    vec.push_back(tt);
}

void bar(int *) {
}

int main(int argc, char *argv[])
{
    std::vector<int*> vec;
    foo(vec);

    return 0;
}

but gcc is still totally blind to the int * overload:

error: cannot convert int* to float* for argument 1 to void bar(float*)

It seems gcc will only use those functions that are defined before the template itself.

However, if you remove the explicit :: specifier and make it just bar(tt), it seems to work fine. Chris Dodd's answer seems satisfactory in explaining why this is so.

casablanca
I suspect that VC++ is wrong here. It simply doesn't bother with the two-phase compilation of templates and dependent/non-dependent things at all. Comeau agrees with GCC. - As to removing `::`, I guess this leaves the option open that a suitable `bar` will be found later using argument-dependent look-up (perhaps it will be found in the namespace T belongs to).
UncleBens
+5  A: 

From section 14.7.2 of the C++ spec:

In an expression of the form:

    postfix-expression ( expression-listopt )

where the postfix-expression is an unqualified-id but not a template-id , the unqualified-id denotes a dependent name if and only if any of the expressions in the expression-list is a type-dependent expression (14.7.2.2).

since ::b is not an unqualified id, it is not a dependent name. If you remove the ::, it is an unqualified name and so is a dependent name. For a non-dependent name, the lookup occurs at the point of the template declaration, not the instantiation, and at that point there is no global declaration of bar visible, so you get an error.

Chris Dodd
The compiler always needs to check that a name has been declared whether or not it is dependent. Name lookup and overload resolution are two different things. The former happens at template definition, the latter at instantiation.
Potatoswatter
-1 There is no such wording in the C++98 standard. There was a correction for C++03 but I don't know what. My best guess is that you've looked in some C++0x draft. In the C++98 standard it's §14.6.2 which says, "In an expression of the form *postfix-expression ( expression-list )* where the *postfix-expression* is an *identifier*, the identifier denotes a *dependent-name* if and only if any of the expressions in the *expression-list* is a type-dependent expression (14.6.2.2)". Lemme check... Yeah, your wording is present in §14.***6***.2 of the ***C++0x*** draft. Uh, I tried to remove downvote
Alf P. Steinbach
@Alf amusingly, the most recent draft n3126 does say id-expression instead of unqualified-id or identifier. This was changed by [#448](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#448) . But it won't do anything to the code of the questioner: Albeit the name will become dependent, the declaration won't be found because ADL won't do anything for qualified names.
Johannes Schaub - litb
Interesting, but what about this from Stroustrup TC++PL Sp Ed, Section C.13.8.1, Dependent Names: "Basically, the name of a function called is dependent if it is obviously dependent by looking at its arguments or at its formal parameters".
Shawn Yarbrough
@Alf This makes me wonder about the committee comment "A related issue is a call with a qualified name and dependent arguments, e.g., x::y(depa, depb)". Apparently they weren't thinking this comment through, because they *effectively* can only consider declarations from the template definition context anyway when the name is qualified.
Johannes Schaub - litb
In fact, now that they have that handling for qualified function calls, they cannot find functions of dependent base classes anymore, because they don't know the base classes in the definition context yet.
Johannes Schaub - litb
This answer seems invalid. First, the incomplete C++0x Standard is not helpful here, I'm only concerned with C++03 or C++98, i.e. real compilers and real standards. Second, @Alf §14.6.2 defines my call to ::bar(TT*) as a dependent function. Third removing the global :: qualifier is not an option for me personally and furthermore seems misguided in general, as the compiler has plenty of information at the point of instantiation to resolve the global form of the call correctly. If ::bar(TT*) is truly not allowed by the Standard, please confirm that Standard is broken?
Shawn Yarbrough
FYI, the reason I can't remove the :: is that in my real code, the template function foo is a member function of class CC, and there exist a family of overloaded member functions CC::bar(...), meaning I need to qualify ::bar(TT*) to avoid defaulting to CC::bar(...). That's what :: exists for, I'm surprised if the Standard says I can't use :: here, and nobody has yet pointed out any part of the current Standard that says I can't.
Shawn Yarbrough
@Alf: the number comes from a (probably somewhat old) draft. However, it doesn't matter whether its *identifier*, *identifier-id* or *id-expression* -- none of those allow scoping prefix like `::`, so with an explicit `::`, its not a dependent name
Chris Dodd
@Chris not true. `::bar` is an *id-expression*.
Johannes Schaub - litb
+1  A: 

A dependent name still requires a function declaration. Any function declaration with that name will do, but there must be something. How else would the compiler disambiguate an overloaded function call from, say, a misspelled functor object? In other words, finding some function of that name, thus verifying that overloading on that name is possible, instigates the overload resolution process in qualified (or unqualified) name lookup.

// hello.cpp

#include <vector>

void bar(); // Comeau bails without this.

template<typename TT> void foo(std::vector<TT*> &vec)
{
    TT *tt;
    ::bar(tt);
    vec.push_back(tt);
}

class Blah
{
};

void bar(Blah *&)
{
}

int main(int argc, char *argv[])
{
    std::vector<Blah*> vec;
    //foo(vec); - instanting it is certainly an error!

    return 0;
}
Potatoswatter
Under gcc 4.4.3, your code gives the error `"too many arguments to function 'void bar()'"` for line 10 `::bar(tt)`. I'm interested in your idea that the symbol bar needs to be partially bound to a family of overloaded functions during parsing of the template, but I find that behavior surprising if true, and at least under gcc my code works if the `::` is deleted. (This code is a simplified example, for my real code I need the `::` so nobody bother suggesting that, please.)
Shawn Yarbrough
@Shawn: Don't know what to say. I didn't try on GCC, my comment is based on having read that part of the Standard recently and trying on Comeau. I do know that it's illegal without any declaration. I'm not sure whether GCC is allowed to give you `too many arguments`, would have to go back and read more closely. (Don't plan to :v( .)
Potatoswatter
+2  A: 

This ugliness works with Intel C++ 11.0 and perhaps illuminates the compiler's point of view:

#include <vector>
#include <iostream>

// *********************
// forward declare in the global namespace a family of functions named bar
// taking some argument whose type is still a matter of speculation
// at this point
template<class T>
void bar(T x);
// *********************

template<typename TT>
void foo(std::vector<TT*> &vec)
{
   TT *tt;
   ::bar(tt);
   vec.push_back(tt);
}

class Blah
{
  public:
};

void bar(Blah *x)
{
  // I like output in my examples so I added this
  std::cout << "Yoo hoo!" << std::endl;
}

// **********************
// Specialize bar<Blah*>
template<>
inline
void bar<Blah*>(Blah *x) { ::bar(x); }
// **********************

int main(int, char *)
{
  std::vector<Blah*> vec;
  foo(vec);

  return 0;
}
Thomas L Holaday
+3  A: 

Nobody has yet pointed out any part of the current Standard that says I can't.

In C++03, the name in the function call ::bar(tt) is nondependent. C++03 does not make the name ::bar dependent. Dependency happens for type names by dependent types, and for non-type names by dependent expressions that are either type or value dependent. If a name is looked up in a dependent type, it becomes a type-dependent id-expression (14.6.2.2/3 last bullet), and its lookup is delayed until instantiation. The name ::bar is no such dependent expression. If you were to call bar(tt), a special rule of C++03 at 14.2.6 says

In an expression of the form:

postfix-expression ( expression-listopt )

where the postfix-expression is an identifier, the identifier denotes a dependent name if and only if any of the expressions in the expression-list is a type-dependent expression (14.6.2.2).

So you need to remove the :: in order to make it an identifier and to make it dependent by this special rule.

The reason I can't remove the :: is that in my real code, the template function foo is a member function of class CC, and there exist a family of overloaded member functions CC::bar(...), meaning I need to qualify ::bar(TT*) to avoid defaulting to CC::bar(...). That's what :: exists for, I'm surprised if the Standard says I can't use :: here

The proper way to solve it is to introduce a using declaration into the local scope of your function.

namespace dummies { void f(); }
template<typename T>
struct S {
  void f();
  void g() { 
    using dummies::f; // without it, it won't work
    f(T()); // with ::f, it won't work
  }
};

struct A { };
void f(A) { } // <- will find this

int main() {
  S<A> a;
  a.g();
}

ADL will not do anything if ordinary lookup finds a class member function. Therefor, you introduce a using declaration, so ordinary lookup doesn't find a class member function, and ADL can advance the declarations visible when instantiating.

But this seems to disagree with you: Stroustrup TC++PL Sp Ed, Section C.13.8.1, Dependent Names: "Basically, the name of a function called is dependent if it is obviously dependent by looking at its arguments or at its formal parameters"

Stroustrup's book is far from being authorative on this. It's written for people who possibly don't know C++ yet. It won't try to be 100% correct with regards to these questions, and it certainly isn't.

Also, the formal parameters of a function have nothing to do with whether a function call is dependent or not. In the IS, only actual arguments define dependency of a function name. This was different in an old draft from 1996, which had the notion of implicit and explicit dependency. Implicitly dependency was defined as

A name implicitly depends on a template-argument if it is a function name used in a function call and the function call would have a dif- ferent resolution or no resolution if a type, template, or enumerator mentioned in the template-argument were missing from the program.

[...]

[Example: some calls that depend on a template-argument type T are:

  1. The function called has a parameter that depends on T according to the type deduction rules (temp.deduct). For example, f(T), f(Array), and f(const T*).

  2. The type of the actual argument depends on T. For example, f(T(1)), f(t), f(g(t)), and f(&t) assuming that t has the type T.

A practical example is also given

This ill-formed template instantiation uses a function that does not depend on a template-argument:

template<class T> class Z {
public:
        void f() const
        {
                g(1); // g() not found in Z's context.
                      // Look again at point of instantiation
        }
};

void g(int);
void h(const Z<Horse>& x)
{
        x.f(); // error: g(int) called by g(1) does not depend
               // on template-argument ``Horse''
}

The call x.f() gives rise to the specialization:

void Z<Horse>::f() { g(1); }

The call g(1) would call g(int), but since that call does not depend on the template-argument Horse and because g(int) was not in scope at the point of the definition of the template, the call x.f() is ill- formed.

On the other hand:

void h(const Z<int>& y)
{
        y.f(); // fine: g(int) called by g(1) depends
               // on template-argument ``int''
}

Here, the call y.f() gives rise to the specialization:

void Z<int>::f() { g(1); }

The call g(1) calls g(int), and since that call depends on the tem- plate-argument int, the call y.f() is acceptable even though g(int) wasn't in scope at the point of the template definition. ]

These things are left to history, and even the last traces from it are disappearing slowly, albeit not actively driven (n3126 for instance gets rid of "explicitly depends" at [temp.names]/p4 as a side-effect of another change, because the distinction between "explicitly depends" and "implicitly depends" has never existed in the IS).

Johannes Schaub - litb
Regarding `@Chris showed you the part of the Standard that`: @Chris showed me a wording from the not-yet-competed C++0x Standard that @Alf quickly pointed out was different from the current, real Standard -- where my code is correct (according to C++98 §14.6.2). Also, my code is intuitively correct. Qualification should not affect template symbol dependence or independence for any reason I've heard so far. At the point of instantiation, the compiler has plenty of information to correctly resolve ::bar(TT*).
Shawn Yarbrough
Regarding ADL, are you saying I should add `using ::bar` into the top of template function foo? Because I tried that and it doesn't work on gcc.
Shawn Yarbrough
@Shawn a dummy `bar` function needs to be declared before your template, that you then bring into local scope by such a using-declaration. Regarding 14.6.2: Show us how you conclude that your code is valid according to that paragraph (by modifying your question). It does not help if you just keep tell us that your code is valid according to it. I have shown you that 14.6.2 only applies to identifiers, and "::bar" is not an identifier. I also showed you that ADL will not do anything for qualified names. If you reject what I say, I can't help you.
Johannes Schaub - litb
I'm studying your information in detail, but I confess I don't understand why people keep bringing up C++0X. It might help if you or anyone could show a simple modification to my 2nd code example in the original question that will provide the behavior I want. Or, if you can show me where the Standard says that there's no way to get the behavior I want, then I will accept that answer, but that would mean C++ templates are horribly mis-designed. I've tried adding a `void bar(int*) {}` and a `using ::bar;` with no luck. The compiler still resolves bar too early.
Shawn Yarbrough
@Shawn I think it's much clearer now.
Johannes Schaub - litb
Works for me now with `using ::bar` if I call `bar(TT*)` instead of `::bar(TT*)`. If I understand correctly: it's not enough that your function call inside a template includes a template parameter (and is a dependent expression), C++ won't always wait to bind the function call because maybe you wanted to pass a delayed-bound template parameter into an immediately-bound function call. It seems perverse to me that applying the ::operator isn't a valid workaround, but a usable workaround does exist in creating a dummy function to kick the C++ overload resolution rules into the correct mode.
Shawn Yarbrough