开发者

member function chosen over the function with the same name in the member function definition

开发者 https://www.devze.com 2023-04-04 12:56 出处:网络
Assume I have a function: template<class T> void save(aType var1, aType var2, T varT) // var1, var2 - do not matter

Assume I have a function:

template<class T>
void save(aType var1, aType var2, T varT) // var1, var2 - do not matter
  {
  // ...
  }

Now I have the class, which defines this function for itself, as the member function

class A {
  public:
  ....
  void save(aType var1, aType var2); // the same as before; only 2 arguments
};

Here is the implementation of the member-function class:

// A.cpp
#include "save.h"
#include "A.h"
void A::save(aType var1, aType var2){开发者_Go百科

  save(var1,var2,one-of-the-members); // here we try to call templated function
}

As a result, compiler says no matching function for call to A::save(var1,var2,var3) candidate is: A::save(var1,var2); That is compiler tries to use the member-function of class A (in the implementation of this function)- with 2 arguments, but looks like it does not see templated version for 3 arguments. How to make that templated version win over the member-function?

Edit: Thanks for all previous answers. The methods suggested still do not help. Well, not actually. Here are some more details/questions:

In addition to templated version:

template<class T>
void save(aType var1, aType var2, T varT) // var1, var2 - do not matter
{
// ...
}

i also overloaded the function for some more specific types, so I also have:

void save(aType var1, aType var2, Type1 varT);
void save(aType var1, aType var2, Type2 varT);
void save(aType var1, aType var2, Type3 varT);
...

The methods suggested (e.g. using :: to bring global scope) help if I comment the templated definition, otherwise there are some unrelated compiler errors. So my next question is: is it possible to overload the function and have its templated version? They seem to be competing.

I also thought about doing run-type identification of the types (of the variable varT):

if(typeid(varT).name()==type_name_1){  ... }
else if(typeid(varT).name()==type_name_2){ ... }
...

but I think this will be inefficient, so this is not good approach. So what i want to do it to use templated version for basic types (int, double, etc.)- so not to overload for each type explicitly - and use my own functions to deal with more complex types. Is is possible to do this efficiently? Thanks in advance.


Either explicitly qualify the call, or bring it into scope with a using declaration.

Explicit qualification:

::save(var1,var2,one-of-the-members);

Using declaration:

using ::save;


::save(var1,var2,one-of-the-members);

The :: qualifier will match a free function, rather than a member function. BTW: your issue has nothing to do with templates. It's a member function / free function issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消