How to resolve name conflict between class name and function name Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to resolve name conflict between class name and function name without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Is there any (good) way of having equally named class and global function in the same namespace in C++?

Below code does not compile because it favors function over class name.

void PrintNumber( int val ) 
{ 
  std::cout << "from function: " << val << std::endl;
}
struct PrintNumber {
  void operator()( int val ) const 
  { 
    std::cout << "from operator: " << val << std::endl;
  }
};

int main()
{
  auto f1 = std::function<void(int)>( PrintNumber() ) ; // Functor class instance // ERROR occurs here
  auto f2 = std::function<void(int)>( PrintNumber ) ;   // Global function
  f1( 123 );
  f2( 456 );
  cin.get();
}

Answer

Use the full name struct PrintNumber. This can’t be done directly in your initialization of std::function:

#include<iostream>
#include<functional>

struct PrintNumber {
  void operator()( int val ) const
  {
    std::cout << "from operator: " << val << std::endl;
  }
};
void PrintNumber( int val )
{
  std::cout << "from function: " << val << std::endl;
}

int main()
{
  struct PrintNumber p;
  auto f1 = std::function<void(int)>( p ) ; // Functor class instance occurs here
  auto f2 = std::function<void(int)>( PrintNumber ) ;   // Global function
  f1( 123 );
  f2( 456 );
  std::cin.get();
}

though probably best to change names or namespaces to avoid ambiguity.

We are here to answer your question about How to resolve name conflict between class name and function name - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji