0

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(); } 
2
  • 2
    Not an answer to the question, but the obvious solution would be to rename the class to NumberPrinter or similar. PrintNumber isn't a good class name. Commented Mar 8, 2020 at 10:28
  • 2
    Rename class/structure like CNumberPrinter to StructNumberPrinter Commented Mar 8, 2020 at 10:34

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.