Reputation: 103
I have written a class that uses literal operators to indicate a measurement error to be used in physical applications. I have defined a literal ""_err
that takes long double
as an argument and returns a struct called Error
. For instance, 1.3_err
.
A friend
declaration for this literal is placed in the header file TStat.h
, and the definition is placed in TStat.cpp
, as you'll see in the code below.
However, I got an error when compiling with an example like b = 0.4_err
where b
is Error
. In the error it says it couldn't find the literal operator. You may check the error message at the end of this question.
I have tried many combinations, like defining the literal internally or externally, etc. I have searched similar questions but everything seems fine in the code, just like it is described by many tutorials and other C++ sources.
As a particle physicist, I use a C/C++ library called ROOT developed by CERN which is actually a C/C++ interpreter. There, I could use this class without any errors (I haven't used any ROOT class at all). However, when I compile my code by g++
with c++11
flag, no match for the literal could be found.
This is the header file:
#ifdef TSTAT_H
#define TSTAT_H
namespace TStat {
struct Error {
// ...
}
class Double {
// constructors, etc.
// ...
friend Error operator "" _err (long double);
}
}
and this is the TStat.cpp file:
#include "TStat.h"
using namespace TStat;
// ...
TStat::Error operator"" _err(long double err) {
TStat::Error error;
// ...
return error;
}
When compiled with the following command in the terminal (I am using MacOS)
g++ -Wall -g -std=c++11 example.cpp TStat.cpp -o example.exe
I get an error saying
example.cpp:6:12: error: no matching literal operator for call to
'operator""_err' with argument of type 'long double' or
'const char *', and no matching literal operator template
b = 0.4_err;
for an example.cpp like this:
#include "TStat.h"
using namespace TStat;
int main() {
Error b;
b = 0.4_err;
return 0;
}
Upvotes: 0
Views: 863
Reputation: 120079
A friend
declaration does not bring the declared name in any other scope. In this case, it doesn't even bring the name in the scope of the class itself:
[class.friend]/7 A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not (6.4.1).
but that's irrelevant for the case shown. main
won't see any friend
declaration in any class.
The easiest fix is to declare operator "" _err
in TStat.h
at the top level outside of any class.
Upvotes: 2