How to choose a class optimally at compile time aka class-overload-set?

SOLVED

I know that there is a way to achieve the following code where the compiler chooses the best fit function for the arguments using overloaded lambdas

auto foo_wrapper = FunctionWrapper([](int a) { return a+1;},
    [](double b) { return b/2; });
assert(foo_wrapper(3.0) - foo_wrapper(0) == 0.5);

The links to read more about this trick are at the bottom of this question

However, is there a trick to let the compiler choose the class of an object from a list of classes based on the functions called?

class Foo { v(int); };
class Bar { p(int); v(int); };

auto foobar_wrapper = ClassWrapper(Foo, Bar);
// some syntax trick here to achieve the equivalent of the following
// Some class to take them as input by comma separated values would also be ok
{
foobar_wrapper x;
x.v();
static_assert(std::is_same_v<decltype(x), Foo>);
}
{
foobar_wrapper y;
y.p();
y.v();
static_assert(std::is_same_v<decltype(x), Bar>);
}
// No need to expose the internal x and y variables
// Can't access x and y here

This will essentially allow me to choose a class without mutex if none of the functions to lock are called.

Given that I don't care about the internal layout of the variable (ie I'm not sprinkling memcpy), what options are available for me to let the compiler decide the best class from a ranked list of candidates?

Is something like this even possible without explicit help from compiler (like syntax such as exceptions, coroutines, etc.)? Would any of the introspection features (metaclass and others) being discussed help in achieving this?

Further reading (for some reason, inlining the links wasn't working)

  1. https://cpptruths.blogspot.com/2014/05/fun-with-lambdas-c14-style-part-2.html
  2. https://martinecker.com/martincodes/lambda-expression-overloading/
  3. https://stackoverflow.com/a/32476942

EDIT:

Found the answer. It's complicated. But, for details, please watch https://www.youtube.com/watch?v=WBTNCYT20f0

Posted Sep 2, 2019, 12:43 PM UTC · edited

211
Ayjayz•

Nothing I'm aware of, and I don't know of any proposals that would help. Are there any languages that do this? I'd be interested. Seems like it might useful.

I can't think of any way to get even close to what you're asking, really. In C++, files compile sequentially and types are chosen when the compiler reaches the code without looking any further. The two main exceptions to that that I'm aware of are template SFINAE and function auto return types, and I can't think how to use either of them to help here.

2
codingateOP•

Languages with a 2 step compilation (JIT/interpreter) or frameworks built for this purpose often do this. In the first pass they log all functions used and build a call-graph and when the evaluate function is called, they create an object of the required type and execute the call graph. This is usually not elegant or generic code.

Tensorflow had a flow like this. AFAIK almost all JS engines like JavaScript Core, SpiderMonkey and V8 claim to perform such features like choosing the optimal object layouts (functions, classes, null: all are objects) based on runtime usage statistics (not exactly compile time) in their multi-tiered JIT/interpreter loops

template SFINAE and function auto return types

Thanks for the HUGE hint. I've put together a maybe correct prototype of what's required. The following code will not compile, but should show what's on my mind right now

// Since Lambda are anonymous, each lambda would create a new class with a unique return type
class_factory = []<class ... Alternatives, class T>(T lambda_input) {
    // overload set to get output of lambda block passed to it
    p = overload {[]<Alternatives...>(auto func){return std::enable_if_t<(func(Alternatives...()), true), Alternatives...>(); }...};
    // This should pass the our code to an overload set which checks if our code with each alternative is correct
    // If not, then it doesn't select it. Else it default constructs an object of that type
    // The best match lambda gives the best match object of the class
    return p(input);
}

auto variable = class_factory<Foo, Bar>([](){// our requirement code});
[](){ // our actual impl code }(variable);
// These 2 lambda might be the same

Right now, the issue is the overload class which needs to behave more like an overload_list instead of the overload_set behavior I've linked to.

EDIT: It's a wrap. Found the video. It describes almost everything required. https://www.youtube.com/watch?v=WBTNCYT20f0

1
Xeverous•

choose the class of an object from a list of classes based on the functions called?

I don't get this. If you simply want to choose a type depending on its member functions, you can use is-detected idiom with SFINAE.

1
codingateOP•

With SFINAE, the class selection doesn't happen based on usage. You have to do ClassWrapper<???> x; x.v(); // x.p(); to choose. That implies knowledge of the future use. In the lambda overload, you define the overload set beforehand and then call the appropriate one at a later date. I wish for a similar functionality with classes

1
Xeverous•

I don't get then what are you trying to make.

is there a trick to let the compiler choose the class of an object from a list of classes based on the functions called?

You have to do ClassWrapper<???> x; x.v(); // x.p(); to choose. That implies knowledge of the future use.

You want multiple wrappers merged into one type? Because I don't see any other way. One wrapper means you need to know earlier which functions are going to be used.

1
codingateOP•

One wrapper means you need to know earlier which functions are going to be used

I know that. However, I'm looking (asking around?) for a way to create a lazy class (sort of) similar to how lambda overloading works. I don't know a way to do this but this doesn't imply that no such way exists. Like I said in my question, would this even be possible currently (and in future)?

I'm not particularly attached to a fixed syntax, as long as the compiler chooses the correct type for me.

You want multiple wrappers merged into one type?

I want a uniform code for multiple use cases.

struct data_mutex {
  private: 
    mutex m;
    data d;
  public:
    data& d_lock() { m.lock(); return d; }
    void d_release() { m.release(); }
};
struct data {
  private: 
    data d;
  public:
    data& d() { return d; }
};

[auto or using] p = SOME_MACRO_OR_CLASS(data_mutex, data);

// Type 1
p variable1, variable2;
ANOTHER_WRAPPER(p)(variable1.d(););
ANOTHER_WRAPPER(p)(variable2.d_lock(); variable2.d_release(););
// Type 2
YET_ANOTHER_WRAPPER(p, variable)(variable.d(););
YET_ANOTHER_WRAPPER(p, variable)(variable.d_lock(); variable.d_release(););

I'm ok with macro tricks or putting code in lambdas or any other trick as long as the class is chosen transparently depending on a usage.

1
Xeverous•

I need more information. I like the example with data and data_mutex but the macros are an implementation detail. Show me how would you use the thing (not how to potentially implement or declare dependencies) and I will figure how it implement it.

1