c++literalsuser-defined-literals

User-defined literal doesn't work when the body is written in a different .cpp file


I created a user-defined literal like this, in is OWN .cpp file (declared as a friend function in .h file):

fraction operator"" _frac(const long double val)
{
    return fraction(static_cast<float>(val));
}

But in main it produces this error:

Error (active)E2486 user-defined literal operator not found

But, when I write the SAME code (definitely the same, as I copy it, and also do some words comparison) in main or .h(outside of the class scope) file, it works fine, why?

I'm using Visual Studio 2019 and C++20 (GitHub Files).

Test.h:

#pragma once
class test
{
    double x;
public:
    explicit test(const double a) : x(a) {};
    friend test operator "" _t(long double a);
};

Test.cpp:

#include "Test.h"

test operator "" _t(const long double a)
{
    return test(a);
}

main:

#include "Test.h"

int main()
{
    test t = 12_t; //error
}

Yes, I know that this is due to the fact that it doesn't have a parameter which is a class, which makes it internal to the class. I want to ask how to declare this in the .cpp file but still be acessible from main (declaration and friend keywords in .h doesn't matter).

What I have tried:


Solution

  • The user-defined literal function just is not declared in your main.cpp.

    Place

    test operator "" _t(const long double a);
    

    in your test.h