Home > Mobile >  C : Have a class always cast as specified type
C : Have a class always cast as specified type

Time:10-30

So I am not sure if this is at all possible in C , but I would like to ensure that a class is always cast as another type by default. Here is an example of what I would imagine this looks like:

class A : public always_cast<std::string> {
private:
    std::string *actualData = new std::string("foo");
public:
    operator std::string &(){
        return *this->actualData;
    }
};

void main(){
   A value;
   std::cout << value.append(" bar") << std::endl; // should print "foo bar"
}

Currently, the closest I can get to this behavior is to just override the cast operator, but I have to explicitly cast it in order to access std::string's member functions:

class A {
private:
    std::string *actualData = new std::string("foo");
public:
    operator std::string &(){
        return *this->actualData;
    }
};

void main(){
   A value;
   std::cout << ((std::string) value).append(" bar") << std::endl; // successfully prints "foo bar"
}

This is a simple example of how I would want to use this. I am trying to build a headers-only library involving lots of templates, and the "always casted" type could be any class type. Although the manual cast is not a deal breaker, it adds an extra step that I would like to allow developers using my library to skip, for their convenience and readability of their code. My library is currently using C 20.

So is there any way to achieve this (or similar) functionality that I cannot think of? Or is this just a pipe dream and I should just settle for having my library just slightly more inconvenient to use?

EDIT: Well alright, I can tell from the context of the responses that this not really possible, and probably not a very good design choice even if I could pull it off. I think the best solution for my use case is to override the -> operator and use that to access the fields, as some people have recommended in the comments.

CodePudding user response:

What you're talking about is broadly conceptualized as the ability to overload "operator dot" in a similar way to how we can overload operator*. There have been many proposals in years past on providing this feature to C , but none of them achieved consensus. My read of the committee is that, like UFCS, they've basically given up on it.

One of the big sticking points has been the question of conflicts. If your class A itself has an append function, which one gets called? Some say that it should always be the converted type; others say that it should always be the main class type; a few others say it should be a compile error.

And no, there is no other way to call a conversion function in order to make .whatever compile. Some "operator dot" suggestions used "base classes" as a way to settle all of the conflict questions (since those have all been answered for base classes), but at present, the language has no way to do what you want.

  • Related