I'm learning C++ with plans to implement it almost entirely in conjunction with R. I get a little tired of appending the namespace "std" to tons of code though. Is there a way to use namespace std for most of the code and switch the namespace to Rcpp just for the compile and sourcing?
Below is a C++ "Hello World" function with namespace Rcpp. This is a trivial example, but lays out the problem. "string" is not a class in Rcpp, so I have to append std:: to it. Again, I know this is a trivial example, but I just want to know if it is possible.
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
std::string hello(std::string x) {
return x;
}
/*** R
hello("Hello World")
*/
Output works as expected, but I'd love if I could make the code look something like this:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
using namespace std;
string hello(string x) {
return x;
}
using namespace Rcpp;
/*** R
hello("Hello World")
*/
This way, as the bulk of the code expands, I don't have to append std to everything.
Related
everyone.
I have learnt that it is often desirable to write in my codes using std::cout instead of using namespace std in order to avoid namespace conflicts. In the following script I only use cout and if I write std:: cout instead of using namespace std; it does not work.
Can anyone please help me understand why? In general, when does std::cout not work and I am forced to use using namespace std?
#include <iostream>
#include <string>
using std::cout; //if writing here "using namespace std;" instead, the code does not work
class MyClass{
public:
string name;
MyClass (string n)
{
name=n;
cout<<"Hello "<<name;
}
};
int main()
{
MyClass MyObj("Mike");
return 0;
}
You need to add using std::string; along with using std::cout; to make it work as you're not only using cout from namespace std, string is also a member of namespace std which you are using in your code.
Your code works okay with:
using std::cout;
statement for cout, but the compiler must know the location of string (actually it's std::string) too which you're currently using. You must define:
using std::string;
When you enter:
using namespace std;
It calls the entire namespace called std which contains a variety of features added as C++ standard library and then you don't need to use prefix std:: for those functions/classes/variables of that namespace.
In TOTW 153 it is claimed that using namespace in function scope can leak in the global scope,
in other words they claim this is:
namespace totw {
namespace example {
namespace {
TEST(MyTest, UsesUsingDirectives) {
using namespace ::testing;
Sequence seq; // ::testing::Sequence
WallTimer timer; // ::WallTimer
}
} // namespace
} // namespace example
} // namespace totw
roughly equivalent to:
using ::testing::Expectation;
using ::testing::Sequence;
using ::testing::UnorderedElementsAre;
...
// many, many more symbols are injected into the global namespace
namespace totw {
namespace example {
namespace {
TEST(MyTest, UsesUsingDirectives) {
Sequence seq; // ::testing::Sequence
WallTimer timer; // ::WallTimer
...
}
} // namespace
} // namespace example
} // namespace totw
So I expected that if I do this it will compile:
#include <gtest/gtest.h>
#include <gmock/gmock.h>
namespace totw {
namespace example {
namespace {
TEST(MyTest, UsesUsingDirectives) {
using namespace ::testing;
Sequence seq; // ::testing::Sequence
}
} // namespace
} // namespace example
} // namespace totw
Sequence s; //notice no testing::
It does not. So I wonder if I am wrong in replicating the example, or is the TOTW153 example misleading?
My best guess is that their example is "wrong" in a sense that what they claim is roughly equivalent is not really equivalent in a sense I would assume it is.
You are correct that the "transpiled" code could lead one to think that your last snippet should work. But that's not what they meant.
The using ::testing::Expectation etc. are added to the global namespace from the perspective of the TEST scope. In other words, the transpiled code is effectively identical to the original only within the TEST scope. Outside of that scope there is no effect, but the problems they list are still problems (unless you know that neither the TEST scope contents nor the contents of any involved namespaces will ever be changed). In other words, the using introduces potential collisions between all (present and future) symbols in that TEST scope and the symbols (present and future) in all the involved namespaces. Sounds less scary but will still bite you in the long run.
I'm writing my functions in C++ to use them in R. Since I don't want to include all the functions inside the same file, I want to call them. I'll give you a simple example of the three files I'm using:
function.h:
#ifndef FUNCTION_H
#define FUNCTION_H
#include <RcppArmadillo.h>
arma::vec quadraticsum(arma::vec x);
#endif
function.cpp:
#include <RcppArmadillo.h>
#include <function.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
using namespace std;
// [[Rcpp::export]]
arma::vec quadraticsum(arma::vec x){
arma::vec results = sum(pow(x,2));
return results;
}
main.cpp:
#include <RcppArmadillo.h>
#include <function.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
using namespace std;
// [[Rcpp::export]]
arma::vec sum2(arma::vec x){
arma::vec results = quadraticsum(x)+2;
return results;
}
I'm working with Rstudio and when I write the code in the main.cpp file it recognizes the function quadraticsum, and so everything seems to be fine. However, when I compile using the command sourceCpp("~/main.cpp"), I got this error:
Error in dyn.load("/private/var/folders/46/1tz_54_n3glfmgftvqsspwrr0000gn/T/Rtmpdnk9hf/sourceCpp-x86_64-apple-darwin13.4.0-0.12.12/sourcecpp_237a88636e6/sourceCpp_2.so") :
unable to load shared object '/private/var/folders/46/1tz_54_n3glfmgftvqsspwrr0000gn/T/Rtmpdnk9hf/sourceCpp-x86_64-apple-darwin13.4.0-0.12.12/sourcecpp_237a88636e6/sourceCpp_2.so':
dlopen(/private/var/folders/46/1tz_54_n3glfmgftvqsspwrr0000gn/T/Rtmpdnk9hf/sourceCpp-x86_64-apple-darwin13.4.0-0.12.12/sourcecpp_237a88636e6/sourceCpp_2.so, 6): Symbol not found: __Z12quadraticsumN4arma3ColIdEE
Referenced from: /private/var/folders/46/1tz_54_n3glfmgftvqsspwrr0000gn/T/Rtmpdnk9hf/sourceCpp-x86_64-apple-darwin13.4.0-0.12.12/sourcecpp_237a88636e6/sourceCpp_2.so
Expected in: flat namespace
in /private/var/folders/46/1tz_54_n3glfmgftvqsspwrr0000gn/T/Rtmpdnk9hf/sourceCpp-x86_64-apple-darwin13.4.0-0.12.12/sourcecpp_237a88636e6/sourceCpp_2.so
Have you seen this problem before? I'm using macOS 10.12.5. Thank you all.
sourceCpp only allows a single source file.
If you want to use multiple source files, you will need to build a full package.
The error appears because the second source file has not been compiled or linked into the shared library. As a result, no function implementation exists.
You could also make the implementations static or inline and then place them in a header, of you want to avoid a full package. if
I discovered that writing #include "function.h" instead of #include <function.h> it compiles correctly. I just changed it. Thank you all.
I am developing a project which works with multiple arithmetic types. So I made a header, where the minimal requirements for a user defined arithmetic type are defined:
user_defined_arithmetic.h :
typedef double ArithmeticF; // The user chooses what type he
// wants to use to represent a real number
namespace arithmetic // and defines the functions related to that type
{
const ArithmeticF sin(const ArithmeticF& x);
const ArithmeticF cos(const ArithmeticF& x);
const ArithmeticF tan(const ArithmeticF& x);
...
}
What is troubling me is that when I use code like this:
#include "user_defined_arithmetic.h"
void some_function()
{
using namespace arithmetic;
ArithmeticF lala(3);
sin(lala);
}
I get a compiler error:
error: call of overloaded 'sin(ArithmeticF&)' is ambiguous
candidates are:
double sin(double)
const ArithmeticF arithmetic::sin(const ArithmeticF&)
I have never used the <math.h> header, only the <cmath>. I have never used the using namespace std in a header file.
I am using gcc 4.6.*. I checked what is the header containing the ambiguous declaration and it turns out to be:
mathcalls.h :
Prototype declarations for math functions; helper file for <math.h>.
...
I know, that <cmath> includes <math.h>, but it should shield the declarations by the std namespace. I dig into the <cmath> header and find:
cmath.h :
...
#include <math.h>
...
// Get rid of those macros defined in <math.h> in lieu of real functions.
#undef abs
#undef div
#undef acos
...
namespace std _GLIBCXX_VISIBILITY(default)
{
...
So the namespace std begins after the #include <math.h>. Is there something wrong here, or did I misunderstand something?
Implementations of the C++ standard library are permitted to declare C library functions in the global namespace as well as in std. Some would call this a mistake, since (as you've found) the namespace pollution can cause conflicts with your own names. However, that's the way it is, so we must live with it. You'll just have to qualify your name as arithmetic::sin.
In the words of the standard (C++11 17.6.1.2/4):
In the C++ standard library, however, the declarations (except for
names which are defined as macros in C) are within namespace scope (3.3.6) of the namespace std. It is
unspecified whether these names are first declared within the global namespace scope and are then injected
into namespace std by explicit using-declarations (7.3.3).
If you really wanted to, you could always write a little wrapper around cmath, along the lines of:
//stdmath.cpp
#include <cmath>
namespace stdmath
{
double sin(double x)
{
return std::sin(x);
}
}
//stdmath.hpp
#ifndef STDMATH_HPP
#define STDMATH_HPP
namespace stdmath {
double sin(double);
}
#endif
//uses_stdmath.cpp
#include <iostream>
#include "stdmath.hpp"
double sin(double x)
{
return 1.0;
}
int main()
{
std::cout << stdmath::sin(1) << std::endl;
std::cout << sin(1) << std::endl;
}
I suppose there could be some overhead from the additional function call, depending on how clever the compiler is.
This is just a humble attempt to start solving this problem. (Suggestions are welcomed.)
I have been dealing with this problem a long time. A case were the problem is very obvious is this case:
#include<cmath>
#include<iostream>
namespace mylib{
std::string exp(double x){return "mylib::exp";}
}
int main(){
std::cout << std::exp(1.) << std::endl; // works
std::cout << mylib::exp(1.) << std::endl; // works
using namespace mylib;
std::cout << exp(1.) << std::endl; //doesn't works!, "ambiguous" call
return 0;
}
This is in my opinion is an annoying bug or at the least an very unfortunate situation. (At least in GCC, and clang --using GCC library-- in Linux.)
Lately I gave it another shot to the problem. By looking at the cmath (of GCC) it seems that the header is there simply to overload the C-functions and screws up the namespace in the process.
namespace std{
#include<math.h>
}
//instead of #include<cmath>
With it this works
using namespace mylib;
std::cout << exp(1.) << std::endl; //now works.
I am almost sure that this is not exactly equivalent to #include<cmath> but most functions seem to work.
Worst of all is that eventually some dependence library will eventually will #inclulde<cmath>. For that I couldn't find a solution yet.
NOTE: Needless to say this doesn't work at all
namespace std{
#include<cmath> // compile errors
}
I am developing a project which works with multiple arithmetic types. So I made a header, where the minimal requirements for a user defined arithmetic type are defined:
user_defined_arithmetic.h :
typedef double ArithmeticF; // The user chooses what type he
// wants to use to represent a real number
namespace arithmetic // and defines the functions related to that type
{
const ArithmeticF sin(const ArithmeticF& x);
const ArithmeticF cos(const ArithmeticF& x);
const ArithmeticF tan(const ArithmeticF& x);
...
}
What is troubling me is that when I use code like this:
#include "user_defined_arithmetic.h"
void some_function()
{
using namespace arithmetic;
ArithmeticF lala(3);
sin(lala);
}
I get a compiler error:
error: call of overloaded 'sin(ArithmeticF&)' is ambiguous
candidates are:
double sin(double)
const ArithmeticF arithmetic::sin(const ArithmeticF&)
I have never used the <math.h> header, only the <cmath>. I have never used the using namespace std in a header file.
I am using gcc 4.6.*. I checked what is the header containing the ambiguous declaration and it turns out to be:
mathcalls.h :
Prototype declarations for math functions; helper file for <math.h>.
...
I know, that <cmath> includes <math.h>, but it should shield the declarations by the std namespace. I dig into the <cmath> header and find:
cmath.h :
...
#include <math.h>
...
// Get rid of those macros defined in <math.h> in lieu of real functions.
#undef abs
#undef div
#undef acos
...
namespace std _GLIBCXX_VISIBILITY(default)
{
...
So the namespace std begins after the #include <math.h>. Is there something wrong here, or did I misunderstand something?
Implementations of the C++ standard library are permitted to declare C library functions in the global namespace as well as in std. Some would call this a mistake, since (as you've found) the namespace pollution can cause conflicts with your own names. However, that's the way it is, so we must live with it. You'll just have to qualify your name as arithmetic::sin.
In the words of the standard (C++11 17.6.1.2/4):
In the C++ standard library, however, the declarations (except for
names which are defined as macros in C) are within namespace scope (3.3.6) of the namespace std. It is
unspecified whether these names are first declared within the global namespace scope and are then injected
into namespace std by explicit using-declarations (7.3.3).
If you really wanted to, you could always write a little wrapper around cmath, along the lines of:
//stdmath.cpp
#include <cmath>
namespace stdmath
{
double sin(double x)
{
return std::sin(x);
}
}
//stdmath.hpp
#ifndef STDMATH_HPP
#define STDMATH_HPP
namespace stdmath {
double sin(double);
}
#endif
//uses_stdmath.cpp
#include <iostream>
#include "stdmath.hpp"
double sin(double x)
{
return 1.0;
}
int main()
{
std::cout << stdmath::sin(1) << std::endl;
std::cout << sin(1) << std::endl;
}
I suppose there could be some overhead from the additional function call, depending on how clever the compiler is.
This is just a humble attempt to start solving this problem. (Suggestions are welcomed.)
I have been dealing with this problem a long time. A case were the problem is very obvious is this case:
#include<cmath>
#include<iostream>
namespace mylib{
std::string exp(double x){return "mylib::exp";}
}
int main(){
std::cout << std::exp(1.) << std::endl; // works
std::cout << mylib::exp(1.) << std::endl; // works
using namespace mylib;
std::cout << exp(1.) << std::endl; //doesn't works!, "ambiguous" call
return 0;
}
This is in my opinion is an annoying bug or at the least an very unfortunate situation. (At least in GCC, and clang --using GCC library-- in Linux.)
Lately I gave it another shot to the problem. By looking at the cmath (of GCC) it seems that the header is there simply to overload the C-functions and screws up the namespace in the process.
namespace std{
#include<math.h>
}
//instead of #include<cmath>
With it this works
using namespace mylib;
std::cout << exp(1.) << std::endl; //now works.
I am almost sure that this is not exactly equivalent to #include<cmath> but most functions seem to work.
Worst of all is that eventually some dependence library will eventually will #inclulde<cmath>. For that I couldn't find a solution yet.
NOTE: Needless to say this doesn't work at all
namespace std{
#include<cmath> // compile errors
}