Ask coding questions

← Back to all posts
C++ How to make class method aliases?
xxpertHacker (860)

Say that I have a class like this:

struct str {
    std::size_t size() const { ... }
    std::size_t length() const { ... }
};

How could I make str::length an alias to str::size to de-duplicate code?

Comments
hotnewtop
Coder100 (17038)

erm

struct str {
    std::size_t size() const { ... }
    std::size_t length() const { return size(); }
};

calling a function?

hopefully not too much overhead

xxpertHacker (860)

@Coder100 So I take that as a "no"?

JS allows you to do

const p = str.prototype;
p.length = p.size;
Coder100 (17038)

@xxpertHacker but you can't here
remember the class is static all methods exist?

Coder100 (17038)

maybe hashmap with pointers but that might be worse @xxpertHacker

xxpertHacker (860)

@Coder100 wdym "the class is static"?

...all methods exist

Why can't I make it exist within the class? I don't think I understand what you're trying to say by that. Can you elaborate?

xxpertHacker (860)

@Coder100 I thought about just making it into a function reference, but it wouldn't be a method like that or as a hashmap.

It wouldn't get the this pointer.

xxpertHacker (860)

@Coder100 Best I've got is this, and it's awful.