c++declarationclang++frienduser-defined-literals

clang c++ friend user defined literal declare failed


namespace ns {
class MyClass {
private:
    int value;
    MyClass(int val) : value(val) {}

    friend MyClass operator"" _myudl(unsigned long long int val); // Friend UDL declaration

    friend MyClass (::operator"" _myudl) (unsigned long long int val); // not working too;

public:
    int getValue() const { return value; }
};
}

// Definition of the friend UDL outside the class
ns::MyClass operator"" _myudl(unsigned long long int val) {
    return ns::MyClass(static_cast<int>(val));
}

int main() {
    ns::MyClass obj = 100_myudl; // Using the friend UDL
    return 0;
}

clang++ -std=c++20, failed, call private constructor; in otherwords, friend declaration failed;
which compiler is right, how fix it by just modify friend declaration;


Solution

  • As often with friend declaration, declare the function before might help:

    namespace ns {
    class MyClass;
    }
    
    ns::MyClass (operator"" _myudl) (unsigned long long int val);
    

    then

    namespace ns {
    class MyClass {
    private:
        int value;
        MyClass(int val) : value(val) {}
    
        friend MyClass (::operator"" _myudl) (unsigned long long int val);
    
    public:
        int getValue() const { return value; }
    };
    }
    
    // Definition of the friend UDL outside the class
    ns::MyClass operator"" _myudl(unsigned long long int val) {
        return ns::MyClass(static_cast<int>(val));
    }
    

    Demo