I'm pretty new to C++, and I'm using std::cout for debugging purposes.
Though, I'd really like to be able to just use cout rather than the whole std::cout thing. I know i could import the std namespace, but I've been explained it was a bad thing due to name clashing that can occur because of this.
Is there anyway to do this?
I tried
std::ostream cout = std::cout;
But I get
function "std::basic_ostream<_CharT, _Traits>::basic_ostream(const std::basic_ostream<_CharT, _Traits> &) [with _CharT=char, _Traits=std::char_traits<char>]" (declared at line 391 of "/usr/include/c++/5/ostream") cannot be referenced -- it is a deleted function
Please suggest.
Sure, with a using declaration:
using std::cout;
Usual health warnings about not doing this in header files, and limiting it to small scopes apply.
You can't copy streams (think about it, it just doesn't make sense), but you can get a reference to them:
std::ostream& my_cout = std::cout;
However, I would strongly advice you not to do so. If you see in some code std::cout you can be almost 100% certain that you know what it is. On the other hand a cout alone you should already look suspicious to you and a my_cout could really be anything. I know it is hard, but get used to type std::, on the long run it will help you more than you need time to type those 5 letters.
Your way would be:
auto& cout = std::cout;
but you might simply do
using std::cout;
(with similar restriction than using namespace: not in namespace scope in header, ideally limiting the scope of using directive as much as possible)
Sorry, too low rating to comment, but why don't you just type
using std::cout;
at the top of the file and then just use cout.
P.S. also answered at this post
One way is using-declaration, which introduces only std::cout instead of all names in std:::
using std::cout;
The way you tried won't work - it's an attempt to copy std::cout to another object - and std::cout is not copyable.
Alternative is to use a reference:
std::ostream& cout = std::cout;
Now, cout points to std::cout instead of being its copy.
The second way can be useful, if you want to, for example, write a function without deciding whether it should output to cout, file or something else:
void func(std::ostream& output) {
output << "works with cout, files, etc.";
}
If you're looking to abbreviate std::cout, it could be that what you are really looking for is dependency injection.
Remember that std::cout is a reference to a model of a std::ostream.
We can use that in our favour to make code more re-usable, testable and loosely coupled.
example:
#include <iostream>
#include <sstream>
std::ostream& do_something(std::ostream& os)
{
os << "Hello, World!\n";
return os;
}
int main()
{
// inject std::cout
do_something(std::cout);
// inject a stringstream
std::ostringstream ss;
do_something(ss);
std::cout << ss.str();
}
So I just started teaching myself C++ and I have two newbie questions regarding the Hello World exercise.
#include <iostream>
using namespace std; [1]
int main()
{
cout << "Hello, World" << endl; [2]
return 0;
}
[1] Is this line of code necessary? If not, why? It worked without it but I found a source that used it and was wondering why was this used.
[2] On my first try I forgot to add endl and the code worked. When I went to check I realised this was missing so why did it still work anyway?
Really basic questions but I want to understand the basics well.
Many thanks in advance.
Is this line of code necessary? If not, why? It worked without it but I found a source that used it and was wondering why was this used.
Namespace
First of all you should have to understand what a namespace is.
That's an argument reference:
Namespace.
Pratically a namespace is like a container. You can keep different
symbol's names. In that way, in very large project, it is possible define two different symbols (e.g two functions) with the same name.
I try to give you a little example:
I can define two different functions foo with the same name. It possibile because I put them inside two different namespaces.
namespace my_ns1 {
void foo(int a) {
return a;
}
}
namespace my_ns2 {
void foo(int a) {
return a + 2;
}
}
When I want to call the first foo function the proper invokation
will be:
my_ns1::foo(10); // return 10
If i want to call the second foo function, then:
my_ns2::foo(10); // return 12
In a specific block I can specify the intent to use always a namespace
with the code:
using namespace my_ns1;
In that way there is no more need to specify the "full name" of the function.
The standard library keeps all its function in a proper namespace: std.
So when you want to use a function in the standard library you have to invoke it with something like:
std::function(...)
If you use the code
using namespace std;
At the begin of your file, you're just saying to "open" that namespace
and you can call all function without std::
The namespace is usefull in order to prevent name conflict.
[2] On my first try I forgot to add endl and the code worked. When I went to check I realised this was missing so why did it still work anyway?
Simply
std::endl
is a proper way to insert the '\n' character which means "an end of line".
Certain situations in my code, I end up invoking the function only if that function is defined, or else I should not. How can I achieve this?
like:
if (function 'sum' exists ) then invoke sum ()
Maybe the other way around to ask this question is how to determine if function is defined at runtime and if so, then invoke?
When you declare 'sum' you could declare it like:
#define SUM_EXISTS
int sum(std::vector<int>& addMeUp) {
...
}
Then when you come to use it you could go:
#ifdef SUM_EXISTS
int result = sum(x);
...
#endif
I'm guessing you're coming from a scripting language where things are all done at runtime. The main thing to remember with C++ is the two phases:
Compile time
Preprocessor runs
template code is turned into real source code
source code is turned in machine code
runtime
the machine code is run
So all the #define and things like that happen at compile time.
....
If you really wanted to do it all at runtime .. you might be interested in using some of the component architecture products out there.
Or maybe a plugin kind of architecture is what you're after.
Using GCC you can:
void func(int argc, char *argv[]) __attribute__((weak)); // weak declaration must always be present
// optional definition:
/*void func(int argc, char *argv[]) {
printf("FOUND THE FUNCTION\n");
for(int aa = 0; aa < argc; aa++){
printf("arg %d = %s \n", aa, argv[aa]);
}
}*/
int main(int argc, char *argv[]) {
if (func){
func(argc, argv);
} else {
printf("did not find the function\n");
}
}
If you uncomment func it will run it otherwise it will print "did not find the function\n".
While other replies are helpful advices (dlsym, function pointers, ...), you cannot compile C++ code referring to a function which does not exist. At minimum, the function has to be declared; if it is not, your code won't compile. If nothing (a compilation unit, some object file, some library) defines the function, the linker would complain (unless it is weak, see below).
But you should really explain why you are asking that. I can't guess, and there is some way to achieve your unstated goal.
Notice that dlsym often requires functions without name mangling, i.e. declared as extern "C".
If coding on Linux with GCC, you might also use the weak function attribute in declarations. The linker would then set undefined weak symbols to null.
addenda
If you are getting the function name from some input, you should be aware that only a subset of functions should be callable that way (if you call an arbitrary function without care, it will crash!) and you'll better explicitly construct that subset. You could then use a std::map, or dlsym (with each function in the subset declared extern "C"). Notice that dlopen with a NULL path gives a handle to the main program, which you should link with -rdynamic to have it work correctly.
You really want to call by their name only a suitably defined subset of functions. For instance, you probably don't want to call this way abort, exit, or fork.
NB. If you know dynamically the signature of the called function, you might want to use libffi to call it.
I suspect that the poster was actually looking for something more along the lines of SFINAE checking/dispatch. With C++ templates, can define to template functions, one which calls the desired function (if it exists) and one that does nothing (if the function does not exist). You can then make the first template depend on the desired function, such that the template is ill-formed when the function does not exist. This is valid because in C++ template substitution failure is not an error (SFINAE), so the compiler will just fall back to the second case (which for instance could do nothing).
See here for an excellent example: Is it possible to write a template to check for a function's existence?
use pointers to functions.
//initialize
typedef void (*PF)();
std::map<std::string, PF> defined_functions;
defined_functions["foo"]=&foo;
defined_functions["bar"]=&bar;
//if defined, invoke it
if(defined_functions.find("foo") != defined_functions.end())
{
defined_functions["foo"]();
}
If you know what library the function you'd like to call is in, then you can use dlsym() and dlerror() to find out whether or not it's there, and what the pointer to the function is.
Edit: I probably wouldn't actually use this approach - instead I would recommend Matiu's solution, as I think it's much better practice. However, dlsym() isn't very well known, so I thought I'd point it out.
You can use #pragma weak for the compilers that support it (see the weak symbol wikipedia entry).
This example and comment is from The Inside Story on Shared Libraries and Dynamic Loading:
#pragma weak debug
extern void debug(void);
void (*debugfunc)(void) = debug;
int main() {
printf(“Hello World\n”);
if (debugfunc) (*debugfunc)();
}
you can use the weak pragma to force the linker to ignore unresolved
symbols [..] the program compiles and links whether or not debug()
is actually defined in any object file. When the symbol remains
undefined, the linker usually replaces its value with 0. So, this
technique can be a useful way for a program to invoke optional code
that does not require recompiling the entire application.
So another way, if you're using c++11 would be to use functors:
You'll need to put this at the start of your file:
#include <functional>
The type of a functor is declared in this format:
std::function< return_type (param1_type, param2_type) >
You could add a variable that holds a functor for sum like this:
std::function<int(const std::vector<int>&)> sum;
To make things easy, let shorten the param type:
using Numbers = const std::vectorn<int>&;
Then you could fill in the functor var with any one of:
A lambda:
sum = [](Numbers x) { return std::accumulate(x.cbegin(), x.cend(), 0); } // std::accumulate comes from #include <numeric>
A function pointer:
int myFunc(Numbers nums) {
int result = 0;
for (int i : nums)
result += i;
return result;
}
sum = &myFunc;
Something that 'bind' has created:
struct Adder {
int startNumber = 6;
int doAdding(Numbers nums) {
int result = 0;
for (int i : nums)
result += i;
return result;
}
};
...
Adder myAdder{2}; // Make an adder that starts at two
sum = std::bind(&Adder::doAdding, myAdder);
Then finally to use it, it's a simple if statement:
if (sum)
return sum(x);
In summary, functors are the new pointer to a function, however they're more versatile. May actually be inlined if the compiler is sure enough, but generally are the same as a function pointer.
When combined with std::bind and lambda's they're quite superior to old style C function pointers.
But remember they work in c++11 and above environments. (Not in C or C++03).
In C++, a modified version of the trick for checking if a member exists should give you what you're looking for, at compile time instead of runtime:
#include <iostream>
#include <type_traits>
namespace
{
template <class T, template <class...> class Test>
struct exists
{
template<class U>
static std::true_type check(Test<U>*);
template<class U>
static std::false_type check(...);
static constexpr bool value = decltype(check<T>(0))::value;
};
template<class U, class = decltype(sum(std::declval<U>(), std::declval<U>()))>
struct sum_test{};
template <class T>
void validate_sum()
{
if constexpr (exists<T, sum_test>::value)
{
std::cout << "sum exists for type " << typeid(T).name() << '\n';
}
else
{
std::cout << "sum does not exist for type " << typeid(T).name() << '\n';
}
}
class A {};
class B {};
void sum(const A& l, const A& r); // we only need to declare the function, not define it
}
int main(int, const char**)
{
validate_sum<A>();
validate_sum<B>();
}
Here's the output using clang:
sum exists for type N12_GLOBAL__N_11AE
sum does not exist for type N12_GLOBAL__N_11BE
I should point out that weird things happened when I used an int instead of A (sum() has to be declared before sum_test for the exists to work, so maybe exists isn't the right name for this). Some kind of template expansion that didn't seem to cause problems when I used A. Gonna guess it's ADL-related.
This answer is for global functions, as a complement to the other answers on testing methods. This answer only applies to global functions.
First, provide a fallback dummy function in a separate namespace. Then determine the return type of the function-call, inside a template parameter. According to the return-type, determine if this is the fallback function or the wanted function.
If you are forbidden to add anything in the namespace of the function, such as the case for std::, then you should use ADL to find the right function in the test.
For example, std::reduce() is part of c++17, but early gcc compilers, which should support c++17, don't define std::reduce(). The following code can detect at compile-time whether or not std::reduce is declared. See it work correctly in both cases, in compile explorer.
#include <numeric>
namespace fallback
{
// fallback
std::false_type reduce(...) { return {}; }
// Depending on
// std::recuce(Iter from, Iter to) -> decltype(*from)
// we know that a call to std::reduce(T*, T*) returns T
template <typename T, typename Ret = decltype(reduce(std::declval<T*>(), std::declval<T*>()))>
using return_of_reduce = Ret;
// Note that due to ADL, std::reduce is called although we don't explicitly call std::reduce().
// This is critical, since we are not allowed to define any of the above inside std::
}
using has_reduce = fallback::return_of_reduce<std::true_type>;
// using has_sum = std::conditional_t<std::is_same_v<fallback::return_of_sum<std::true_type>,
// std::false_type>,
// std::false_type,
// std::true_type>;
#include <iterator>
int main()
{
if constexpr (has_reduce::value)
{
// must have those, so that the compile will find the fallback
// function if the correct one is undefined (even if it never
// generates this code).
using namespace std;
using namespace fallback;
int values[] = {1,2,3};
return reduce(std::begin(values), std::end(values));
}
return -1;
}
In cases, unlike the above example, when you can't control the return-type, you can use other methods, such as std::is_same and std::contitional.
For example, assume you want to test if function int sum(int, int) is declared in the current compilation unit. Create, in a similar fashion, test_sum_ns::return_of_sum. If the function exists, it will be int and std::false_type otherwise (or any other special type you like).
using has_sum = std::conditional_t<std::is_same_v<test_sum_ns::return_of_sum,
std::false_type>,
std::false_type,
std::true_type>;
Then you can use that type:
if constexpr (has_sum::value)
{
int result;
{
using namespace fallback; // limit this only to the call, if possible.
result = sum(1,2);
}
std::cout << "sum(1,2) = " << result << '\n';
}
NOTE: You must have to have using namespace, otherwise the compiler will not find the fallback function inside the if constexpr and will complain. In general, you should avoid using namespace since future changes in the symbols inside the namespace may break your code. In this case there is no other way around it, so at least limit it to the smallest scope possible, as in the above example
I have a code like below:
typedef std::set<std::string> set_of_strings;
set_of_strings s1, s2, result1;
some_func()
{
s1.insert("1-2");
s1.insert("1-1");
s1.insert("3-4");
s2.insert("1-2");
s2.insert("1-3");
s2.insert("3-4");
set_of_strings::iterator s1_begin = s1.begin();
set_of_strings::iterator s1_end = s1.end();
set_of_strings::iterator s2_begin = s2.begin();
set_of_strings::iterator s2_end = s2.end();
set_of_strings::iterator result_begin = result1.begin();
td::insert_iterator<set_of_strings> result_inserter = std::inserter(result1, result_begin);
set_difference(s1_begin, s1_end,s2_begin, s2_end,result_inserter); //This is the problem line
}
The compilation error that i get is overloading ambiguity std::copy(....
the problem is set_difference returns like
return copy(first1,last1,result);
Please check here for the algo rithm of set_difference.
set_difference returns like :
copy(..)
if it is std::copy there would not be any problem.
i tried with putting my statement inside a block like below:
{
using namespace std;
set_difference(s1_begin, s1_end,s2_begin, s2_end,result_inserter);
}
but this doesn't work.
I know that the problem is with the copy function which we have written for our own purpose and its used at many places.Here i want to use std::copy.
could anybody pls help.
If you've written your own copy function that the compiler can see in the same scope as std::copy and it's a possible candidate, then sure that would cause an ambiguity.
There's no magic flag you can set to make it use std::copy, but I think if you put your own copy in a namespace and don't using that namespace, the compiler won't be able to find it and fall back to std::copy. That said, I don't think I can understand a case where you would want to create an alternate copy that works for set iterators, and if you wrote a generic one it probably shouldn't be called copy because it'll cause no end of ambiguity errors like this one.
I stumbled on a strange compilation problem. I want to process a list of strings, using std::for_each. The following simplified code illustrates the problem :
# include <list>
# include <string>
# include <algorithm>
using namespace std ;
void f(wstring & str)
{
// process str here
}
void g(wstring & str, int dummy = 0)
{
// process str here, same as f, just added a second default dummy argument
}
int main(int, char*[])
{
list<wstring> text ;
text.push_back(L"foo") ;
text.push_back(L"bar") ;
for_each(text.begin(), text.end(), f) ; // OK, fine :)
for_each(text.begin(), text.end(), g) ; // Compilation error, complains about
// g taking 2 arguments, but called within std::for_each
// with only one argument.
// ...
return 0 ;
}
I tested using MinGW 4.5.2 and MSVC10, both reported the same error message. Originally, I wanted to use boost::algorithm::trim as a processing function passed to std::for_each, but I found that it takes two arguments, the first being mandatory (the string to process) and the second one is optional (a locale providing a definition for space chars).
Is there any way to keep things clean when using std::for_each(and other standard algorithms) when having functions or methods with default arguments ? I found a way to make it work, but it is no more clear and easily understandable, so a for loop begins to seem easier ...
# include <list>
# include <string>
# include <algorithm>
# include <boost/bind.hpp>
# include <boost/algorithm/string.hpp>
using namespace std ;
using namespace boost ;
// ... somewhere inside main
list<wstring> text ;
for_each(text.begin(), text.end(), bind(algorithm::trim<wstring>, _1, locale()) ;
// One must deal with default arguments ...
// for_each(text.begin(), text.end(), algorithm::trim<wstring>) would be a real pleasure
Thanks for any help !
Note : I just started learning English, sorry for mistakes :)
Default arguments are just a code-generation tool and not part of the function signature, so you can't really get around that. You could wrap your function in a function object, but that's precisely what bind already does for you.
However, in C++0x you can conveniently store the result (and use std::bind) to maybe make the code a bit more readable:
auto trimmer = std::bind(boost::algorithm::trim<std::wstring>, std::placeholders::_1, std::locale());
std::for_each(text.begin(), text.end(), trimmer);
(The reason you don't want to do that in C++98/03 is that the return type of bind is something rather unsightly, and you wouldn't be doing anyone a favour by spelling it out.)
Alternatively, again in C++0x, you could use a lambda:
std::for_each(text.begin(), text.end(), [](std::wstring & s){ boost::algorithm::trim<std::wstring>(s); });