Class template instantiations and universal references - c++

In a code like this:
template<class...> struct pack{};
template<class, class = int>
struct call_t
{
template<class... args_t>
static int apply(args_t&&...)
{ return 0; }
};
template<class... args_t>
struct call_t<pack<args_t...>, // (1)
std::decay_t<decltype(convert(declval<args_t>()...))> >
{
template<class... params_t> // (2)
static int apply(params_t&&... args)
{ return convert(std::forward<params_t>(args)...); }
};
template<class... args_t>
auto test(args_t&&... args) // (3)
{
return call_t<pack<args_t...> >::
apply(std::forward<args_t>(args)...);
}
This function sends a pack of params to a function or another according to if a function convert exists and can be called with the passed params, keeping intact (I guess) their exact passed types, and when its return type is int, irrespective of reference or const qualifiers.
I have three doubts with that piece of code.
(1) Is declval return type still a universal reference? For instance, declval<T>(), with T = int&, will its return type be int&& (a true r-value reference), or int & && and be deduced again as int& following the usual rules of universal references when passing to another call? I supposed that it doesn't (as pointed out by #101010), but I don't know in that case how to make a perfect overloading test.
(2) Do I need to re-specify the variadic template to use the universal reference deduction rules, or since the correct types have been already deduced in (3), they keep their deduced types intact?
Or can I just write
template<class... args_t>
struct call_t<pack<args_t...>, // (1)
std::decay_t<decltype(convert(declval<args_t>()...))> >
{
// (2)
static int apply(args_t... args)
{ return convert(args...); }
};
?
The call_t template class is an implementation detail, so, it will be instantiate only inside test.

Those two cases are not equivalent. This example:
template<class... args_t>
struct call_t<pack<args_t...>, // (1)
std::decay_t<decltype(convert(declval<args_t>()...))> >
{
// (2)
static int apply(args_t... args)
{ return convert(args...); }
};
does not forward anything. The parameter pack args... are lvalues, because they have names. That is very different than this code:
template<class... params_t> // (2)
static int apply(params_t&&... args)
{ return convert(std::forward<params_t>(args)...); }
in which args... is forwarded. The resulting behavior is that the new example could be slower than the old example (doing copies instead of moves) or could simply surprisingly fail to compile. Consider convert(std::unique_ptr<int> ). That is invocable with args_t = {std::unique_ptr<int>}, but the internal apply() would fail because you'd be trying to copy the unique_ptr.
You'd need to do:
static int apply(args_t... args)
{ return convert(std::forward<args_t>(args)...); }

Related

How to correctly forward and use a nested tuple of constexpr struct with standard tuple operations

I want to store passed data via constexpr constructor of a struct, and store the data in a std::tuple, to perform various TMP / compile time operations.
Implementation
template <typename... _Ts>
struct myInitializer {
std::tuple<_Ts...> init_data;
constexpr myInitializer(_Ts&&... _Vs)
: init_data{ std::tuple(std::forward<_Ts>(_Vs)...) }
{}
};
Stored data uses a lightweight strong type struct, generated via lvalue and rvalue helper overload:
template <typename T, typename... Ts>
struct data_of_t {
using type = T;
using data_t = std::tuple<Ts...>;
data_t data;
constexpr data_of_t(Ts&&... _vs)
: data(std::forward<Ts>(_vs)...)
{}
};
template<typename T, typename... Ts>
constexpr auto data_of(Ts&&... _vs) {
return data_of_t<T, Ts...>(std::forward<Ts>(_vs)...);
};
template<typename T, typename... Ts>
constexpr auto data_of(Ts&... _vs) {
return data_of_t<T, Ts...>(std::forward<Ts>(_vs)...);
};
It's implemented like
template <typename T = int>
class test {
public:
static constexpr auto func(int p0=0, int p1=1, int p2=3) noexcept {
return data_of <test<T>>
(data_of<test<T>>(p0, p1));
}
};
int main() {
constexpr // fails to run constexpr // works without
auto init = myInitializer (
test<int>::func()
,test<int>::func(3)
,test<int>::func(4,5)
);
std::apply([&](auto&&... args) {
//std::cout << __PRETTY_FUNCTION__ << std::endl;
auto merged_tuple = std::tuple_cat(std::forward<decltype(args.data)>(args.data)...);
}
, init.init_data);
}
Getting to the point
std::tuple_cat fails if myInitializer instance is constexpr.
std::apply([&](auto&&... args) {
auto merged_tuple = std::tuple_cat(std::forward<decltype(args.data)>(args.data)...);
It appears to be related to the const qualifier added via constexpr.
How can this be fixed?
See full example at https://godbolt.org/z/j5xdT39aE
This:
auto merged_tuple = std::tuple_cat(std::forward<decltype(args.data)>(args.data)...);
is not the right way to forward data. decltype(args.data) is going to give you the type of that data member - which is not a function of either the const-ness or value category of args. Let's take a simpler example:
void f(auto&& arg) {
g(std::forward<decltype(arg.data)>(arg.data));
}
struct C { int data; };
C c1{1};
const C c2{2};
f(c1);
f(c2);
f(C{3});
So here I have three calls to f (which call f<C&>, f<const C&>, and f<C>, respectively). In all three cases, decltype(arg.data) is... just int. That's what the type of C::data is. But that's not how it needs to be forwarded (it won't compile for c2 because we're trying to cast away const-ness -- as in your example -- and it'll erroneously move out of c1).
What you want is to forward arg, separately, and then access data:
void f(auto&& arg) {
g(std::forward<decltype(arg)>(arg).data);
}
Now, decltype(arg) actually varies from instantiation to instantiation, which is a good indicator that we're doing something sensible.
In addition of the forwarding problem denoted by Barry, there's a different reason why you cannot have constexpr on init. This is because you contain a reference to a temporary inside data_of_t.
You see, you are containing a type obtained from overload resolution from a forwarding reference:
template<typename T, typename... Ts>
constexpr auto data_of(Ts&&... _vs) {
return data_of_t<T, Ts...>(std::forward<Ts>(_vs)...);
};
The Ts... in this case could be something like int, float const&, double&. You send those reference type and then you contain them inside of the std::tuple in data_of_t.
Those temporaries are local variables from the test function:
template <typename T = int>
class test {
public:
static constexpr auto func(int p0=0, int p1=1, int p2=3) noexcept {
return data_of <test<T>>
(data_of<test<T>>(p0, p1));
}
};
The problem here is that p0, p1, p2 are all local variable. You send them in test_of_t which will contain references to them, and you return the object containing all those reference to the local variable. This is maybe the cause of the MSVC crash. Compiler are required to provide diagnostic for any undefined behaviour in constexpr context. This crash is 100% a compiler bug and you should report it.
So how do you fix that?
Simply don't contain references by changing data_of:
template<typename T, typename... Ts>
constexpr auto data_of(Ts&&... _vs) {
return data_of_t<T, std::decay_t<Ts>...>(std::forward<Ts>(_vs)...);
};
This will decay the type thus removing the references and decay any reference to C array to pointers.
Then, you have to change your constructor. You call std::forward in there but it's no forwarding occurring if you decay in the template arguments.
template<typename... Vs> requires((std::same_as<std::decay_t<Vs>, Ts>) && ...)
constexpr data_of_t(Vs... _vs)
: data(std::forward<Vs>(_vs)...)
{}
This will add proper forwarding and also constrain it properly so it always do as data_of intended.
Just doing those change will remove UB from the code, but also change it a bit. The type data_of_t will always contain values, and won't contain references. If you want to send a reference, you will need something like std::ref, just like std::bind have to use to defer parameters.
You will still need to use std::forward<decltype(arg)>(arg).data for proper forwarding as #Barry stated

"Empty base optimization" for lambda captures - forbidden by the Standard? Why?

I recently came across a situation where I ended up with a large number of nested lambdas to build asynchronous computation chains.
template <typename F>
struct node : F
{
node(F&& f) : F{std::move(f)}
{
}
template <typename FThen>
auto then(FThen&& f_then)
{
return ::node{[p = std::move(*this), t = std::move(f_then)]()
{
}};
}
};
int main()
{
auto f = node{[]{ }}.then([]{ }).then([]{ });
return sizeof(f);
}
All the objects I capture in my the lambdas are empty, yet the size of the final object is greater than one: example on gcc.godbolt.org.
If I change the lambda inside node</* ... */>::then to a function object with explicit EBO, the size of the final object becomes one.
template <typename P, typename T>
struct node_lambda : P, T
{
node_lambda(P&& p, T&& t) : P{std::move(p)}, T{std::move(t)}
{
}
void operator()()
{
}
};
template <typename FThen>
auto node</* ... */>::then(FThen&& f_then)
{
return ::node{node_lambda{std::move(*this), std::move(f_then)}};
}
Live example on gcc.godbolt.org
I find this really annoying because I'm forced to either:
Write a lot of boilerplate code that is roughly equivalent to the lambda.
Pay an additional memory cost due to the fact that something like EBO doesn't apply to lambda captures.
Is there anything in the Standard that explicitly forces empty lambda captures to take additional space? If so, why?
From expr.prim.lambda.capture:
For each entity captured by copy, an unnamed non-static data member is declared in the closure type.
While the lambdas here have no capture:
auto f = node{[]{ }}.then([]{ }).then([]{ });
and hence have no unnamed non-static data members, and hence are empty, that's not what then() actually uses. It uses this:
return ::node{[p = std::move(*this), t = std::move(f_then)](){}};
that lambda captures t and p by copy, and hence has two unnamed non-static data members. Each .then() adds another member variable, even if each one is empty, hence the size of the node keeps going up.
Or in other words, the empty base optimization only applies to bases, and capture for lambdas doesn't create bases, it creates non-static data members.
The other answers have the cause, so I will not re-iterate. I will just add that I was able to turn your example into an inheritance based one without too much boilerplate. Since you do public inheritance in the OP, I opted to remove the c'tor and go for aggregate initialization.
It only required two deduction guides to make the code almost as pretty as your original scheme:
Live on Coliru
#include <utility>
#include <iostream>
struct empty {
void operator()() {}
};
template <typename P, typename T>
struct node : P, T
{
template <typename FThen>
auto then(FThen&& f_then)
{
return ::node{std::move(*this), std::forward<FThen>(f_then)};
}
void operator()() {
P::operator()();
T::operator()();
}
};
template <typename P> node(P) -> node<P, ::empty>;
template <typename P, typename T> node(P, T) -> node<P, T>;
int main()
{
auto f = node{[]{ }}.then([]{ }).then([]{ });
std::cout << sizeof(f);
}
The EBO was applied, as you can see by following the link.
BTW, since we are are moving *this, it may be worth to r-value qualify node::then. Just to avoid any nastiness.
Given the as-if rule and [expr.prim.lambda.closure]/2:
An implementation may define the closure type differently from what is
described below provided this does not alter the observable behavior
of the program other than by changing:
the size and/or alignment of the closure type,
whether the closure type is trivially copyable (Clause [class]),
whether the closure type is a standard-layout class (Clause [class]), or
whether the closure type is a POD class (Clause [class]).
I don't see anything preventing an implementation from using some kind of magic to optimize away the storage for the captured empty variable.
That said, doing so would be an ABI break, so don't hold your breath.
Allowing - or requiring - an implementation to make the type of a captured empty variable a base of the closure type, on the other hand, would be a horrendously bad idea. Consider:
struct X { };
struct Y { };
void meow(X x); // #1
void meow(Y y); // #2
void meow(std::function<void()> f); // #3
template<class T, class U>
void purr(T t, U u) {
meow([t = std::move(t), u = std::move(u)] { /* ... */ });
}
It would be insane for purr to do anything other than call #3, yet if captures can become bases then it can call #1, or #2, or be ambiguous.
As others have noted, lambdas are specified to capture as member variables not as bases. So you are out of luck.
What you could do is take a page from bind.
Suppose you have a tuple that does use empty base optimization. Then we can write a helper:
template<class Sig>
struct lambda_ebo_t;
template<class F, class...Args>
struct lambda_ebo_t<F(Args...)>:
private std::tuple<Args...>,
private F
{
decltype(auto) operator()(){
return std::apply( (F&)*this, (std::tuple<Args...>&)*this );
}
template<class...Ts>
lambda_ebo_t( F f, Ts&&...ts ):
std::tuple<Args...>( std::forward<Ts>(ts)... ),
F( std::move(f) )
{}
};
template<class F, class...Args>
lambda_ebo_t<F, std::decay_t<Args>...>
lambda_ebo( F f, Args&&...args ) {
return {std::move(f), std::forward<Args>(args)...};
}
That is a bunch of boilerplate, and incomplete (reference capture may not work right even if you use std::ref), but it gives us:
template <typename FThen>
auto then(FThen&& f_then)
{
return ::node{lambda_ebo([](auto&& p, auto&& t)
{
}, std::move(*this), std::move(f_then))};
}
where we store the data outside the lambda and pass it in as arguments to the lambda. The storage uses EBO.
No need to write a custom EBO class for each lambda, just a few hoops to jump through when you need a lambda with EBO enabled.
This is one without using the tuple, but it doesn't support fundamantal types like int or other things you cannot derive from:
template<class Sig>
struct lambda_ebo_t;
template<class F, class...Args>
struct lambda_ebo_t<F(Args...)>:
private Args...,
// private std::tuple<Args...>,
private F
{
decltype(auto) operator()(){
//return std::apply( (F&)*this, (std::tuple<Args...>&)*this );
return ((F&)(*this))((Args&)*this...);
}
template<class...Ts>
lambda_ebo_t( F f, Ts&&...ts ):
Args(std::forward<Ts>(ts))...,
F( std::move(f) )
{}
};
template<class F, class...Args>
lambda_ebo_t<F(std::decay_t<Args>...)>
lambda_ebo( F f, Args&&...args ) {
return {std::move(f), std::forward<Args>(args)...};
}
Live example, with this test code:
auto test = lambda_ebo( [](auto&&...args){std::cout << sizeof...(args) << "\n";}, []{} , []{}, []{}, []{}, []{}, []{}, []{}, []{}); //
std::cout << "bytes:" << sizeof(test) << "\n";
std::cout << "args:";
test();
sizeof(test) is 1, and it "captures" 8 arguments.
Empty base optimization works for me in the following case
#include <utility>
template <typename F>
class Something : public F {
public:
Something(F&& f_in) : F{std::move(f_in)} {}
};
int main() {
auto something = Something{[]{}};
static_assert(sizeof(decltype(something)) == 1);
}
Live example here https://wandbox.org/permlink/J4m4epDUs19kp5CH
My guess is that the reason it's not working in your case is that the lambda you use in the then() method is not actually empty, it has member variables - the ones listed in your capture. So there is no real empty base there.
If you change the last line of your code to just return node{[]{}} then it works. The lambdas used by .then() do not materialize as "empty" classes.
Whereas in the explicit struct case, it has no member variables per se, only classes it derives from, hence empty base optimization can work there.

C++ variadic template arguments method to pass to a method without variadic arguments

I have the following question, I really can't compile from all the questions and articles researched:
In C++, is it possible to have a method with variadic template arguments that specify types of arguments (as a meta-description type for parameters of in, out, in/out of a certain type, to be passed by value, by address etc.), to loop through these variadic arguments in order to instantiate variables of specified types, and be passed these variables to functions specified by a pointer in a template parameter, but these functions not having variadic parameters?
EDIT 1
I try here to detail, as pseudocode:
template <decltype(*Type::*Method), typename... Parameters>
static bool ExecuteMethod(JSContext *cx, unsigned argc, JS::Value *vp)
{
JS::CallArgs args = CallArgsFromVp(argc, vp);
loop through Parameters
{
Parameters[i]::Type p[i] <-- args[i];
}
ReturnType r = Method(p[0], p[1], p[2] .. p[n]); // the method does not have variadic parameters
...
}
where Method might be like:
int(*GetColor) ( int16 *color);
int(*GetFile) ( FilePath &file );
int(*WriteDocument) ( const FilePath &file, const char *fileFormatName, bool askForParms);
etc.
This comes out of wrapping needs.
The challenge is something missing in C++, reflection as in .net.
It is possible to instance an array of heterogeneous objects by looping through the variadic arguments somehow? Probably.
But how pass them to methods having no variadic arguments? I think it is not possible to assign that array of objects to functions like these three above without explicit wrappers, isn't it?
EDIT 2
I've got a lot of feed-back, but it is clear I was not specific enough.
I did not detailed too much because I've got complains in the past for being too specific. Indeed, I do not have easy implementations and I am a generic guy, not lazy, but I try to make a latter development faster.
Here is the source of the problem: I need to wrap Adobe Illustrator API, which exposes hundreds if not thousands of pointers to functions grouped in structs, called suites.
I try to have a javascript engine using SpiderMonkey.
I use Visual Studio 2015 compiler.
My approach is as follows:
I have several classes to wrap the API in order to add to SpiderMonkey's engine objects for all the suites. Each SpiderMonkey class, could be called as jsData, wraps a data type of Adobe SDK, or a suite, jsSuite.
So far, I have used templates because SpiderMonkey forces me to add each function to its custom objects with a specific signature, like this:
bool jsAIDocumentSuite::WriteDocument(JSContext *cx, unsigned argc, JS::Value *vp)
{
...
}
and adding it to the custom object would be done like this:
const JSFunctionSpec jsAIDocumentSuite::fFunctions[] = {
...
JS_FN("WriteDocument", jsAIDocumentSuite::WriteDocument, 3, 0),
...
}
JS_FN is a SpiderMonkeyMacro.
Actually, this is, so far, less than 10% of the Adobe SDK.
The most are getters and setters with one parameter, passed by value or address or pointer, so I have replaced them by a generic function, like this:
template <typename jsType, typename jsReturnType, typename ReturnPrivateType = jsReturnType::PrivateType, typename jsParamType, typename ParamPrivateType = jsParamType::PrivateType, ReturnPrivateType(*Type::*Method)(ParamPrivateType&)>
static bool GetByRefMethod(JSContext *cx, unsigned argc, JS::Value *vp)
{
JS::CallArgs args = CallArgsFromVp(argc, vp);
try
{
ReturnPrivateType result;
ParamPrivateType ppt;
if (jsType::Suite() && (jsType::Suite()->*Method))
result = (jsType::Suite()->*Method)(ppt);
else
return false; // TODO throw a meaningful error
if ((jsReturnType::IsNoError(result)) && (argc > 0) && (args[0].isObject()))
{
JSObject *obj = &args[0].toObject();
JSObject *value = NULL;
if (!jsParamType::FromAIObject<jsParamType>(cx, &ppt, value))
return false;
if (!value)
return false;
jsProperty::SetProperty(cx, &obj, "value", value, true);
}
JSObject *obj = JS_NewObject(cx, &jsDataClass<jsReturnType>::fClass);
JS_SetPrivate(obj, new ReturnPrivateType(result));
args.rval().setObject(*obj);
}
EXCEPTION_CATCH_CONVERT();
return true;
}
A bit complicated, isn't it?
What is relevant, above, is:
The args variable holds the SpiderMonkey parameters passed in by its engine
Only one argument is passed here, ppt
The return type is one value, so it is easy to be handled
I use macros to inject the method in its variants (several short forms too, not so interesting here):
JS_FN(#GET_METHOD, (js##TYPE::GetByRefMethod<js##TYPE, RETURN_JS_TYPE, RETURN_PRIVATE_TYPE, PARAM_JS_TYPE, PARAM_PRIVATE_TYPE, &TYPE::GET_METHOD>), 1, 0)
I wish to be able to handle variable arguments, according to the statistics more philosophical, but interesting. The idea would be opposite to the C++, probably, and not as expected.
How would I expect it:
I wish to add variadic parameters meta-information, like:
template
static bool Method(JSContext *cx, unsigned argc, JS::Value *vp)
{
JS::CallArgs args = CallArgsFromVp(argc, vp);
try
{
ReturnPrivateType result;
*1st challenge: Loop through the variadic list of meta-parameters and create their corresponding object instances here and initialize the IN ones with values from the *args* collection passed by the SpiderMonkey engine*
if (jsType::Suite() && (jsType::Suite()->*Method))
result = (jsType::Suite()->*Method)(*2nd challenge: pass arguments here: probably by using a variadic macro?*);
else
return false; // TODO throw a meaningful error
if ((jsReturnType::IsNoError(result)) && (argc > 0) && (args[0].isObject()))
{
JSObject *obj = &args[0].toObject();
JSObject *value = NULL;
if (!jsParamType::FromAIObject<jsParamType>(cx, &ppt, value))
return false;
if (!value)
return false;
jsProperty::SetProperty(cx, &obj, "value", value, true);
}
JSObject *obj = JS_NewObject(cx, &jsDataClass<jsReturnType>::fClass);
JS_SetPrivate(obj, new ReturnPrivateType(result));
args.rval().setObject(*obj);
}
EXCEPTION_CATCH_CONVERT();
return true;
}
As you can see, it is not as C++ expected, it is a bit reversed, by trying to avoid writing templates to deduct the parameters, here, I know the parameters first and try to write a code to generate the right parameters by knowing their meta-information first and I have a clear set of types and I promise to write the right code to generate the correct wrappers. I don't need to validate much regarding the data of the parameters, as things are mostly passed without a huge business logic in the process.
EDIT 3
About the parameters meta-information, I could write a few types with statics to specify the data type of the parameter, whether it is a return type, whether it is an IN, an OUT or an IN/OUT parameter, its jsType etc..
They would be the variadic list of the template parameters function above.
I still am having some difficulty understanding exactly what you want to do, but this should let you call a function(without variardic parameters) using a variardic template function, getting the parameters from an array and allowing a conversion operation to apply to each parameter before being passed to the function:
#include <functional>
template<typename T, typename JST> T getParam(const JST& a)
{
//Do whatever conversion necessary
return a;
}
namespace detail
{
template<typename R, typename... Args, int... S> R jsCaller(std::function<R(Args...)> f, seq<S...>, const JS::CallArgs& args)
{
return f(getParam<Args, /*Whatever type should go here */>(args[S])...);
}
}
//Actually use this to call the function and get the result
template<typename R, typename... Args> R jsCall(std::function<R(Args...)> f, const JS::CallArgs& args)
{
return detail::jsCaller(f, GenSequence<sizeof...(Args)>(), args);
}
Where GenSequence extends seq<0, 1, 2, ... , N - 1> and can be implemented as follows:
template<int... N>
struct seq {};
template<int N, int... S>
struct gens : gens<N-1, N-1, S...> {};
template<int... S>
struct gens<0, S...>
{
typedef seq<S...> type;
};
template<int N> using GenSequence<N> = typename gens<N>::type;
This creates a parameter pack of integers, and expands the function call using them- See this question.
You can call your method using jsCall:
Result r = jsCall((Method), args);
Assuming Method can be converted to std::function- if not, you can still do it by making a lambda which conforms to std::function. Does this solve the problem?
[Continued from part 1: https://stackoverflow.com/a/35109026/5386374 ]
There is an issue, however. We had to change the way our code is written to accomodate ExecuteMethod(), which may not always be possible. Is there a way around that, so that it functions exactly the same as your previously specified ExecuteMethod(), and doesn't need to take the variable it modifies as a macro parameter? The answer is... yes!
// Variadic function-like macro to automatically create, use, and destroy functor.
// Uncomment whichever one is appropriate for the compiler used.
// (The difference being that Visual C++ automatically removes the trailing comma if the
// macro has zero variadic arguments, while GCC needs a hint in the form of "##" to tell
// it to do so.)
// Instead of a do...while structure, we can just use a temporary Executor directly.
// MSVC:
// #define ExecuteMethod(M, ...) Executor<decltype(&M), decltype(&M)>{}(M, __VA_ARGS__)
// GCC:
#define ExecuteMethod(M, ...) Executor<decltype(&M), decltype(&M)>{}(M, ##__VA_ARGS__)
// For your example function WriteDocument(), defined as
// int WriteDocument(const FilePath &file, const char *fileFormatName, bool askForParms);
bool c = ExecuteMethod(WriteDocument, file, fileFormatName, askForParams);
This is all well and good, but there is one more change we can make to simplify things without impacting performance. At the moment, this functor can only take function pointers (and maybe lambdas, I'm not familiar with their syntax), not other types of function objects. If this is intended, it means that we can rewrite it to do away with the first template parameter (the entire signature), since the second and third parameters are themselves components of the signature.
// Default functor.
template<typename... Ts>
struct Executor { };
// General case.
template<typename ReturnType, typename... Params>
struct Executor<ReturnType (*)(Params...)> {
private:
// Instead of explicitly taking M as a parameter, create it from
// the other parameters.
using M = ReturnType (*)(Params...);
public:
// Parameter match:
bool operator()(M method, Params... params) {
ReturnType r = method(params...);
// ...
}
// Parameter mismatch:
template<typename... Invalid_Params>
bool operator()(M method, Invalid_Params... ts) {
// Handle parameter type mismatch here.
}
};
// Special case to catch void return type.
template<typename... Params>
struct Executor<void (*)(Params...)> {
private:
// Instead of explicitly taking M as a parameter, create it from
// the other parameters.
using M = void (*)(Params...);
public:
// Parameter match:
bool operator()(M method, Params... params) {
method(params...);
// ...
}
// Parameter mismatch:
template<typename... Invalid_Params>
bool operator()(M method, Invalid_Params... ts) {
// Handle parameter type mismatch here.
}
};
// Variadic function-like macro to automatically create, use, and destroy functor.
// Uncomment whichever one is appropriate for the compiler used.
// (The difference being that Visual C++ automatically removes the trailing comma if the
// macro has zero variadic arguments, while GCC needs a hint in the form of "##" to tell
// it to do so.)
// Instead of a do...while structure, we can just use a temporary Executor directly.
// MSVC:
// #define ExecuteMethod(M, ...) Executor<decltype(&M)>{}(M, __VA_ARGS__)
// GCC:
#define ExecuteMethod(M, ...) Executor<decltype(&M)>{}(M, ##__VA_ARGS__)
// Note: If your compiler doesn't support C++11 "using" type aliases, replace them
// with the following:
// typedef ReturnType (*M)(Params...);
This results in cleaner code, but, as mentioned, limits the functor to only accepting function pointers.
When used like this, the functor expects parameters to be an exact match. It can handle reference-ness and cv-ness correctly, but may have issues with rvalues, I'm not sure. See here.
As to how to use this with your JSContext... I'm honestly not sure. I haven't learned about contexts yet, so someone else would be more helpful for that. I would suggest checking if one of the other answers here would be more useful in your situation, in all honesty.
Note: I'm not sure how easy it would be to modify the functor to work if its function parameter is a functor, lambda, std::function, or anything of the sort.
Note 2: As before, I'm not sure if there would be any negative effects on performance for doing something like this. There's likely a more efficient way, but I don't know what it would be.
I came up with the following C++11 solution, which gives the basic idea. It could very easily be improved, however, so I welcome suggestions. Live test here.
#include <iostream>
#include <tuple>
using namespace std;
// bar : does something with an arbitrary tuple
// (no variadic template arguments)
template <class Tuple>
void bar(Tuple t)
{
// .... do something with the tuple ...
std::cout << std::tuple_size<Tuple>::value;
}
// foo : takes a function pointer and an arbitrary number of other
// arguments
template <class Func, typename... Ts>
void foo(Func f, Ts... args_in)
{
// construct a tuple containing the variadic arguments
std::tuple<Ts...> t = std::make_tuple(args_in...);
// pass this tuple to the function f
f(t);
}
int main()
{
// this is not highly refined; you must provide the types of the
// arguments (any suggestions?)
foo(bar<std::tuple<int, const char *, double>>, 123, "foobar", 43.262);
return 0;
}
Edit: After seeing your "Edit 2", I don't believe this is the proper solution. Leaving it up for reference, though.
I believe I've found a potential solution that catches reference-ness, too. Scroll down to the bottom, to the "Edit 4" section.
If you're asking whether it's possible to dynamically check template argument types, you can. I'll start with a general example of how to use std::true_type and std::false_type to overload based on whether a specified condition is met, then move on to your problem specifically. Consider this:
#include <type_traits>
namespace SameComparison {
// Credit for the contents of this namespace goes to dyp ( https://stackoverflow.com/a/20047561/5386374 )
template<class T, class...> struct are_same : std::true_type{};
template<class T, class U, class... TT> struct are_same<T, U, TT...> :
std::integral_constant<bool, std::is_same<T, U>{} && are_same<T, TT...>{} >{};
} // namespace SameComparison
template<typename T> class SomeClass {
public:
SomeClass() = default;
template<typename... Ts> SomeClass(T arg1, Ts... args);
~SomeClass() = default;
void func(T arg1);
template<typename U> void func(U arg1);
template<typename... Ts> void func(T arg1, Ts... args);
template<typename U, typename... Ts> void func(U arg1, Ts... args);
// ...
private:
template<typename... Ts> SomeClass(std::true_type x, T arg1, Ts... args);
template<typename... Ts> SomeClass(std::false_type x, T arg1, Ts... args);
// ...
};
// Constructors:
// -------------
// Public multi-argument constructor.
// Passes to one of two private constructors, depending on whether all types in paramater pack match T.
template<typename T> template<typename... Ts> SomeClass<T>::SomeClass(T arg1, Ts... args) :
SomeClass(SameComparison::are_same<T, Ts...>{}, arg1, args...) { }
// All arguments match.
template<typename T> template<typename... Ts> SomeClass<T>::SomeClass(std::true_type x, T arg1, Ts... args) { }
// One or more arguments is incorrect type.
template<typename T> template<typename... Ts> SomeClass<T>::SomeClass(std::false_type x, T arg1, Ts... args) {
static_assert(x.value, "Arguments wrong type.");
}
/*
Note that if you don't need to use Ts... in the parameter list, you can combine the previous two into a single constructor:
template<typename T> template<bool N, typename... Ts> SomeClass<T>::SomeClass(std::integral_constant<bool, N> x, T arg1, Ts... args) {
static_assert(x.value, "Arguments wrong type.");
}
x will be true_type (value == true) on type match, or false_type (value == false) on type mismatch. Haven't thoroughly tested this, just ran a similar function through an online compiler to make sure it could determine N.
*/
// Member functions:
// -----------------
// Single argument, type match.
template<typename T> void SomeClass<T>::func(T arg1) {
// code
}
// Single argument, type mismatch.
// Also catches true_type from multi-argument functions after they empty their parameter pack, and silently ignores it.
template<typename T> template<typename U> void SomeClass<T>::func(U arg1) {
if (arg1 != std::true_type{}) {
std::cout << "Argument " << arg1 << " wrong type." << std::endl;
}
}
// Multiple arguments, argument 1 type match.
template<typename T> template<typename... Ts> void SomeClass<T>::func(T arg1, Ts... args) {
func(arg1);
func(args...);
// func(SameComparison::are_same<T, Ts...>{}, vals...);
}
// Multiple arguments, argument 1 type mismatch.
template<typename T> template<typename U, typename... Ts> void SomeClass<T>::func(U arg1, Ts... args) {
// if (arg1 != std::true_type{}) {
// std::cout << "Argument " << arg1 << " wrong type." << std::endl;
// }
func(vals...);
}
First, SameComparison::are_same there is an extension of std::is_same, that applies it to an entire parameter pack. This is the basis of the check, with the rest of the example showing how it can be used. The lines commented out of the last two functions show how it could be applied there, as well.
Now, onto your problem specifically. Since you know what the methods are, you can make similar comparison structs for them.
int (*GetColor) ( int16_t *color);
int(*GetFile) ( FilePath &file );
int(*WriteDocument) ( const FilePath &file, const char *fileFormatName, bool askForParms);
Could have...
namespace ParameterCheck {
template<typename T, typename... Ts> struct parameter_match : public std::false_type {};
// Declare (GetColor, int16_t*) valid.
template<> struct parameter_match<int (*)(int16_t*), int16_t*> : public std::true_type {};
// Declare (GetFile, FilePath&) valid.
// template<> struct parameter_match<int (*)(FilePath&), FilePath&> : public std::true_type {}; // You'd think this would work, but...
template<> struct parameter_match<int (*)(FilePath&), FilePath> : public std::true_type {}; // Nope!
// For some reason, reference-ness isn't part of the templated type. It acts as if it was "template<typename T> void func(T& arg)" instead.
// Declare (WriteDocument, const FilePath&, const char*, bool) valid.
// template<> struct parameter_match<int (*)(const FilePath&, const char*, bool), const FilePath, const char*, bool> : public std::true_type {};
// template<> struct parameter_match<int (*)(const FilePath&, const char*, bool), const FilePath&, const char*, bool> : public std::true_type {};
template<> struct parameter_match<int (*)(const FilePath&, const char*, bool), FilePath, const char*, bool> : public std::true_type {};
// More reference-as-template-parameter wonkiness: Out of these three, only the last works.
} // namespace ParameterCheck
Here, we make a general-case struct that equates to std::false_type, then specialise it so that specific cases are true_type instead. What this does is tell the compiler, "These parameter lists are good, anything else is bad," where each list starts with a function pointer and ends with the arguments to the function. Then, you can do something like this for your caller:
// The actual calling function.
template<typename Func, typename... Ts> void caller2(std::true_type x, Func f, Ts... args) {
std::cout << "Now calling... ";
f(args...);
}
// Parameter mismatch overload.
template<typename Func, typename... Ts> void caller2(std::false_type x, Func f, Ts... args) {
std::cout << "Parameter list mismatch." << std::endl;
}
// Wrapper to check for parameter mismatch.
template<typename Func, typename... Ts> void caller(Func f, Ts... args) {
caller2(ParameterCheck::parameter_match<Func, Ts...>{}, f, args...);
}
As for return type deduction... that depends on where you want to deduce it:
Determine variable type from contents: Use auto when declaring the variable.
Determine return type from passed function return type: If your compiler is C++14-compatible, that's easy. Just use auto. [VStudio 2015 and GCC 4.8.0 (with -std=c++1y) are compatible with auto return type.]
The former can be done like this:
int i = 42;
int func1() { return 23; }
char func2() { return 'c'; }
float func3() { return -0.0f; }
auto a0 = i; // a0 is int.
auto a1 = func1(); // a1 is int.
auto a2 = func2(); // a2 is char.
auto a3 = func3(); // a3 is float.
The latter, however, is more complex.
std::string stringMaker() {
return std::string("Here, have a string!");
}
int intMaker() {
return 5;
}
template<typename F> auto automised(F f) {
return f();
}
// ...
auto a = automised(stringMaker); // a is std::string.
auto b = automised(intMaker); // a is int.
If your compiler isn't compatible with auto or decltype(auto) return type... well, it's a bit more verbose, but we can do this:
namespace ReturnTypeCapture {
// Credit goes to Angew ( https://stackoverflow.com/a/18695701/5386374 )
template<typename T> struct ret_type;
template<typename RT, typename... Ts> struct ret_type<RT (*)(Ts...)> {
using type = RT;
};
} // namespace ReturnTypeCapture
// ...
std::string f1() {
return std::string("Nyahaha.");
}
int f2() {
return -42;
}
char f3() {
return '&';
}
template<typename R, typename F> auto rtCaller2(R r, F f) -> typename R::type {
return f();
}
template<typename F> void rtCaller(F f) {
auto a = rtCaller2(ReturnTypeCapture::ret_type<F>{}, f);
std::cout << a << " (type: " << typeid(a).name() << ")" << std::endl;
}
// ...
rtCaller(f1); // Output (with gcc): "Nyahaha. (type: Ss)"
rtCaller(f2); // Output (with gcc): "-42 (type: i)"
rtCaller(f3); // Output (with gcc): "& (type: c)"
Furthermore, we can simplify it even more, and check the return type without a separate wrapper.
template<typename F> auto rtCaller2(F f) -> typename ReturnTypeCapture::ret_type<F>::type {
return f();
}
template<typename F> void rtCaller(F f) {
auto a = rtCaller2(f);
std::cout << a << " (type: " << typeid(a).name() << ")" << std::endl;
}
// ...
rtCaller(f1); // Output (with gcc): "Nyahaha. (type: Ss)"
rtCaller(f2); // Output (with gcc): "-42 (type: i)"
rtCaller(f3); // Output (with gcc): "& (type: c)"
// Same output.
Having that sticking off the end there is really ugly, though, so can't we do better than that? The answer is... yes! We can use an alias declaration to make a typedef, leaving a cleaner name. And thus, the final result here is:
namespace ReturnTypeCapture {
// Credit goes to Angew ( https://stackoverflow.com/a/18695701/5386374 )
template<typename T> struct ret_type;
template<typename RT, typename... Ts> struct ret_type<RT (*)(Ts...)> {
using type = RT;
};
} // namespace ReturnTypeCapture
template <typename F> using RChecker = typename ReturnTypeCapture::ret_type<F>::type;
std::string f1() { return std::string("Nyahaha."); }
int f2() { return -42; }
char f3() { return '&'; }
template<typename F> auto rtCaller2(F f) -> RChecker<F> {
return f();
}
template<typename F> void rtCaller(F f) {
auto a = rtCaller2(f);
std::cout << a << " (type: " << typeid(a).name() << ")" << std::endl;
}
So now, if we combine parameter checking & return type deduction...
// Parameter match checking.
namespace ParameterCheck {
template<typename T, typename... Ts> struct parameter_match : public std::false_type {};
// Declare (GetColor, int16_t*) valid.
template<> struct parameter_match<int (*)(int16_t*), int16_t*> : public std::true_type {};
// Declare (GetFile, FilePath&) valid.
template<> struct parameter_match<int (*)(FilePath&), FilePath> : public std::true_type {};
// Declare (WriteDocument, const FilePath&, const char*, bool) valid.
template<> struct parameter_match<int (*)(const FilePath&, const char*, bool), FilePath, const char*, bool> : public std::true_type {};
// Declare everything without a parameter list valid.
template<typename T> struct parameter_match<T (*)()> : public std::true_type { };
} // namespace ParameterCheck
// Discount return type deduction:
namespace ReturnTypeCapture {
// Credit goes to Angew ( https://stackoverflow.com/a/18695701/5386374 )
template<typename T> struct ret_type;
template<typename RT, typename... Ts> struct ret_type<RT (*)(Ts...)> {
using type = RT;
};
} // namespace ReturnTypeCapture
// Alias declarations:
template<typename F, typename... Ts> using PChecker = ParameterCheck::parameter_match<F, Ts...>;
template<typename F> using RChecker = typename ReturnTypeCapture::ret_type<F>::type;
// ---------------
int GetColor(int16_t* color);
int GetFile(FilePath& file);
int WriteDocument(const FilePath& file, const char* fileFormatName, bool askForParams);
std::string f1() { return std::string("Nyahaha."); }
int f2() { return -42; }
char f3() { return '&'; }
// ---------------
// Calling function (C++11):
// The actual calling function.
template<typename Func, typename... Ts> auto caller2(std::true_type x, Func f, Ts... args) -> RChecker<Func> {
std::cout << "Now calling... ";
return f(args...);
}
// Parameter mismatch overload.
template<typename Func, typename... Ts> auto caller2(std::false_type x, Func f, Ts... args) -> RChecker<Func> {
std::cout << "Parameter list mismatch." << std::endl;
return static_cast<RChecker<Func> >(0); // Just to make sure we don't break stuff.
}
// Wrapper to check for parameter mismatch.
template<typename Func, typename... Ts> auto caller(Func f, Ts... args) -> RChecker<Func> {
// return caller2(ParameterCheck::parameter_match<Func, Ts...>{}, f, args...);
return caller2(PChecker<Func, Ts...>{}, f, args...);
}
// ---------------
// Calling function (C++14):
// The actual calling function.
template<typename Func, typename... Ts> auto caller2(std::true_type x, Func f, Ts... args) {
std::cout << "Now calling... ";
return f(args...);
}
// Parameter mismatch overload.
template<typename Func, typename... Ts> auto caller2(std::false_type x, Func f, Ts... args) {
std::cout << "Parameter list mismatch." << std::endl;
}
// Wrapper to check for parameter mismatch.
template<typename Func, typename... Ts> auto caller(Func f, Ts... args) {
// return caller2(ParameterCheck::parameter_match<Func, Ts...>{}, f, args...);
return caller2(PChecker<Func, Ts...>{}, f, args...);
}
You should be able to get the functionality you want out of this, I believe. The only caveat is that if you do it this way, you need to explicitly declare functions valid in ParameterCheck, by making a template specialisation for the function & its parameter list, derived from std::true_type instead of std::false_type. I'm not sure if there's a way to get true dynamic parameter list checking, but it's a start.
[I'm not sure if you can just overload caller() or if you explicitly need to use caller2() as well. All my attempts to overload caller() via template parameters ended up crashing the compiler; for some reason, it chose template<typename Func, typename... Ts> void caller(Func f, Ts... args) as a better match for caller(std::true_type, f, args...) than template<typename Func, typename... Ts> caller(std::true_type x, Func f, Ts... args), even with the latter listed before the former, and tried to recursively expand it until it ran out of memory. (Tested on two online gcc compilers: Ideone, and TutorialsPoint's compiler (with -std=c++11). I'm not sure if this is a gcc problem, or if I was a bit off about how template matching works. Unfortunately, the online VStudio compiler is down for maintenance, and the only version of VS I have available to me offline at the moment doesn't support variadic templates, so I can't check which is the case.) Unless someone says otherwise, or says how to fix that particular issue, it's probably best to just use caller() as a wrapper & caller2() to do the heavy lifting.]
Examples of pretty much everything here that would be relevant to your problem: here
Also, note that you can't easily pull individual arguments from a parameter pack. You can use recursion to strip arguments off the front a few at a time, you can use them to initialise member variables in a constructor's initialisation list, you can check how many arguments are in the pack, you can specialise it (as we did for parameter_match), & you can pass the whole pack to a function that takes the right number of arguments, but I believe that's it at the moment. This can make them a bit more awkward than C-style varargs at times, despite being more efficient. However, if your ExecuteMethod()'s argument list consists of a function and its argument list, and nothing else, this isn't an issue. As long as the parameter match succeeds, we can just give the entire pack to the passed function, no questions asked. On that note, we can rewrite ExecuteMethod() into something like...
// Not sure what cx is, leaving it alone.
// Assuming you wanted ExecuteMethod to take parameters in the order (cx, function, function_parameter_list)...
// Parameter list match.
template<typename M, typename... Parameters>
static bool ExecuteMethodWorker(std::true_type x, JSContext* cx, M method, Parameters... params)
{
auto r = method(params...);
// ...
}
// Parameter list mismatch.
template<typename M, typename... Parameters>
static bool ExecuteMethodWorker(std::false_type x, JSContext* cx, M method, Parameters... params)
{
// Handle parameter type mismatch here.
// Omit if not necessary, though it's likely better to use it to log errors, terminate, throw an exception, or something.
}
// Caller.
template<typename M, typename... Parameters>
static bool ExecuteMethod(JSContext* cx, M method, Parameters... params)
{
return ExecuteMethodWorker(PChecker<M, Parameters...>{}, cx, method, params...);
}
Make sure to either prototype or define the worker functions before ExecuteMethod(), so the compiler can resolve the call properly.
(Apologies for any typoes I may have missed anywhere in there, I'm a bit tired.)
Edit: I've located the problem with passing references to a template. It seems that using templates to determine types does indeed remove reference-ness in and of itself, hence notation like template<typename T> void func(T&) for functions that take a reference. Sadly, I'm not yet sure how to fix this issue. I did, however, come up with a new version of PChecker that dynamically reflects types for any function that doesn't use reference types. So far, however, you still need to add references manually, and non-const references probably won't work properly for now.
namespace ParameterCheck {
namespace ParamGetter {
// Based on an answer from GManNickG ( https://stackoverflow.com/a/4693493/5386374 )
// Turn the type list into a single type we can use with std::is_same.
template<typename... Ts> struct variadic_typedef { };
// Generic case, to catch passed parameter types list.
template<typename... Ts> struct variadic_wrapper {
using type = variadic_typedef<Ts...>;
};
// Special case to catch void parameter types list.
template<> struct variadic_wrapper<> {
using type = variadic_typedef<void>;
};
// Generic case to isolate parameter list from function signature.
template<typename RT, typename... Ts> struct variadic_wrapper<RT (*)(Ts...)> {
using type = variadic_typedef<Ts...>;
};
// Special case to isolate void parameter from function signature.
template<typename RT> struct variadic_wrapper<RT (*)()> {
using type = variadic_typedef<void>;
};
} // namespace ParamGetter
template<typename... Ts> using PGetter = typename ParamGetter::variadic_wrapper<Ts...>::type;
// Declare class template.
template<typename... Ts> struct parameter_match;
// Actual class. Becomes either std::true_type or std::false_type.
template<typename F, typename... Ts> struct parameter_match<F, Ts...> : public std::integral_constant<bool, std::is_same<PGetter<F>, PGetter<Ts...> >{}> {};
// Put specialisations for functions with const references here.
} // namespace ParameterCheck
template<typename F, typename... Ts> using PChecker = ParameterCheck::parameter_match<F, Ts...>;
See here.
--
Edit 2: Okay, can't figure out how to grab the passed function's parameter list and use it directly. It might be possible using tuples, perhaps using the rest of GManNickG's code (the convert_in_tuple struct), but I haven't looked into them, and don't really know how to grab the entire type list from a tuple at the same time, or if it's even possible. [If anyone else knows how to fix the reference problem, feel free to comment.]
If you're only using references to minimise passing overhead, and not to actually change data, you should be fine. If your code uses reference parameters to modify the data that the parameter is pointing to, however, I'm not sure how to help you. Sorry.
--
Edit 3: It looks like RChecker might not be as necessary for C++11 function forwarding, we can apparently use decltype([function call]) for that. So...
// caller2(), using decltype. Valid, as args... is a valid parameter list for f.
template<typename Func, typename... Ts> auto caller2(std::true_type x, Func f, Ts... args) -> decltype(f(args...)) {
std::cout << "Now calling... ";
return f(args...);
}
// Parameter mismatch overload.
// decltype(f(args...)) would be problematic, since args... isn't a valid parameter list for f.
template<typename Func, typename... Ts> auto caller2(std::false_type x, Func f, Ts... args) -> RChecker<Func> {
std::cout << "Parameter list mismatch." << std::endl;
return static_cast<RChecker<Func> >(0); // Make sure we don't break stuff.
}
// Wrapper to check for parameter mismatch.
// decltype(caller2(PChecker<Func, Ts...>{}, f, args...)) is valid, but would be more verbose than RChecker<Func>.
template<typename Func, typename... Ts> auto caller(Func f, Ts... args) -> RChecker<Func> {
// return caller2(ParameterCheck::parameter_match<Func, Ts...>{}, f, args...);
return caller2(PChecker<Func, Ts...>{}, f, args...);
}
However, as noted, decltype can have issues when it can't find a function call that matches what it's passed exactly. So, for any case where the parameter mismatch version of caller2() is called, trying to use decltype(f(args...)) to determine return type would likely cause issues. However, I'm not sure if decltype(auto), introduced in C++14, would have that issue.
Also, in C++14-compatible compilers, it's apparently better to use decltype(auto) than just auto for automatic return type determination; auto doesn't preserve const-ness, volatile-ness, or reference-ness, while decltype(auto) does. It can be used either as a trailing return type, or as a normal return type.
// caller2(), using decltype(auto).
template<typename Func, typename... Ts> decltype(auto) caller2(std::true_type x, Func f, Ts... args) {
std::cout << "Now calling... ";
return f(args...);
}
decltype(auto) can also be used when declaring variables. See here for more information.
Edit 4: I believe I may have found a potential solution that preserves the passed function's parameter list properly, using functors. However, it may or may not create unwanted overhead, I'm not sure.
// Default functor.
template<typename... Ts>
struct Executor { };
// General case.
template<typename M, typename ReturnType, typename... Params>
struct Executor<M, ReturnType (*)(Params...)> {
public:
// Parameter match:
bool operator()(M method, Params... params) {
ReturnType r = method(params...);
// ...
}
// Parameter mismatch:
template<typename... Invalid_Params>
bool operator()(M method, Invalid_Params... ts) {
// Handle parameter type mismatch here.
}
};
// Special case to catch void return type.
template<typename M, typename... Params>
struct Executor<M, void (*)(Params...)> {
public:
// Parameter match:
bool operator()(M method, Params... params) {
method(params...);
// ...
}
// Parameter mismatch:
template<typename... Invalid_Params>
bool operator()(M method, Invalid_Params... ts) {
// Handle parameter type mismatch here.
}
};
// Variadic function-like macro to automatically create, use, and destroy functor.
// Uncomment whichever one is appropriate for the compiler used.
// (The difference being that Visual C++ automatically removes the trailing comma if the
// macro has zero variadic arguments, while GCC needs a hint in the form of "##" to tell
// it to do so.)
// Also note that the "do { ... } while (false)" structure is used to swallow the trailing
// semicolon, so it doesn't inadvertently break anything; most compilers will optimise it
// out, leaving just the code inside.
// (Source: https://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html )
// MSVC:
// #define ExecuteMethod(C, M, ...) \
// do { \
// Executor<decltype(&M), decltype(&M)> temp; \
// C = temp(M, __VA_ARGS__); \
// } while (false)
// GCC:
#define ExecuteMethod(C, M, ...) \
do { \
Executor<decltype(&M), decltype(&M)> temp; \
C = temp(M, ##__VA_ARGS__); \
} while (false)
In this case, you can use it as:
ExecuteMethod(return_value_holder, function_name, function_parameter_list);
Which expands to...
do {
Executor<decltype(&function_name), decltype(&function_name)> temp;
return_value_holder = temp(function_name, function_parameter_list);
} while (false);
With this, there's no need to manually go through the parameter pack and make sure each one matches the passed function's parameters. As the passed function's parameter list is quite literally built into Executor as Params..., we can simply overload the function call operator based on whether the arguments it was passed match Params... or not. If the parameters match the function, it calls the Parmas... overload; if they don't, it calls the Invalid_Params... overload. A bit more awkward than true reflection, IMO, but it seems to match everything properly.
Note that:
I'm not sure whether using functors liberally can cause any performance or memory use overhead. I'm... not all that familiar with them at the moment.
I don't know if it's possible to combine the general case and the "void return type" special case into a single functor. The compiler complained when I tried, but I'm not sure if it's because it isn't possible or because I was doing it wrong.
Considering #2, when modifying this version of ExecuteMethod()'s parameters, you have to modify it and both versions of Executor to match.
Like so, where JSContext* cx is added to the parameter list:
template<typename M, typename ReturnType, typename... Params>
struct Executor<M, ReturnType (*)(Params...)> {
public:
bool operator()(JSContext* cx, M method, Params... params);
};
template<typename M, typename... Params>
struct Executor<M, void (*)(Params...)> {
public:
bool operator()(JSContext* cx, M method, Params... params);
};
#define ExecuteMethod(C, cx, M, ...) \
do { \
Executor<decltype(&M), decltype(&M)> temp; \
C = temp(cx, M, ##__VA_ARGS__); \
} while (false)
This may be the solution, but it requires further testing to see if it has any negative impacts on performance. At the very least, it'll make sure const-ness and reference-ness is preserved by ExecuteMethod(), and it's a lot cleaner than my old ideas.
See here.
There are further improvements that can be made, however. As I'm out of space, see here.
Notes:
int16_t (a.k.a. std::int16_t) is in the header <cstdint>.
std::true_type and std::false_type are in the header <type_traits>.
It's difficult to tell from your description, but this is my closest interpretation to what you asked:
auto foo(int) { cout << "foo int" << endl; }
auto foo(float) { cout << "foo float" << endl; }
//... other foo overloads...
template <class T>
auto uber_function(T t)
{
foo(t);
}
template <class T, class... Args>
auto uber_function(T t, Args... args)
{
foo(t);
uber_function(args...);
}
auto main() -> int
{
uber_function(3, 2.4f);
return 0;
}
Of course this can be improved to take references, to make forwarding. This is just for you to have a starting point. As you weren't more clear, I can't give a more specific answer.

How to make a SFINAE-based Y combinator in C++?

I was thinking about the implicit templates of C++14, and I'm trying to declare a function to match an specific argument type (SFINAE and traits still give me headaches). I'm not sure how to explain what I want, but I'm trying to make a Y combinator (just to see if it's possible, not intended for production).
I'm trying to declare a function:
template<typename T>
my_traits<T>::return_type Y(T t) {
// ...
};
Such that T is a function (or a functor) that matches
std::function<R(F, Args...)>
// where F (and above return_type) will be
std::function<R(Args...)>
Which would take any number of arguments, but the first should be a function with the same return type and the same arguments (except this function itself). The first parameter to the operator () of the functor is a template.
The usage I want to achieve:
auto fib = [](auto myself, int x) {
if(x < 2)
return 1;
return myself(x - 1) + myself(x - 2);
};
// The returned type of fib should be assignable to std::function<int(int)>
I wasn't able to take the return type of the T type (because of the overloaded operator ()). What I'm trying to make is possible? How could I make it?
Edit:
Seeing it from a different angle, I'm trying to make this work:
struct my_functor {
template<typename T>
char operator () (T t, int x, float y) { /* ... */ };
};
template<typename T>
struct my_traits {
typedef /* ... */ result_type;
/* ... */
};
// I want this to be std::function<char(int, float)>, based on my_functor
using my_result =
my_traits<my_functor>::result_type;
It is not possible in C++14 return type deduction to deduce int(int) out of int(T, int) as OP desires.
However, we can mask the first parameter of the result using the following approach. The struct YCombinator is instantiated with a non-recursive function object member, whose first argument is a version of itself without the first argument. YCombinator provides a call operator that receives the arguments of the non-recursive function and then returns its function object member after substituting itself for the first argument. This technique allows the programmer to avoid the messiness of myself(myself, ...) calls within the definition of the recursive function.
template<typename Functor>
struct YCombinator
{
Functor functor;
template<typename... Args>
decltype(auto) operator()(Args&&... args)
{
return functor(*this, std::forward<Args>(args)...);
}
};
A make_YCombinator utility template allows for a streamlined usage pattern. This compiles run runs in GCC 4.9.0.
template<typename Functor>
decltype(auto) make_YCombinator(Functor f) { return YCombinator<Functor> { f }; }
int main()
{
auto fib = make_YCombinator([](auto self, int n) -> int { return n < 2 ? 1 : self(n - 1) + self(n - 2); });
for (int i = 0; i < 10 ; ++i)
cout << "fib(" << i << ") = " << fib(i) << endl;
return 0;
}
Since the non-recursive function is not defined at time that the recursive function is defined, in general the recursive function must have an explicit return type.
Edit:
However, it may be possible for the compiler to deduce the return type in certain cases if the programmer takes care to indicate the return type of the recursive function before use of the non-recursive function. While the above construction requires an explicit return type, in the following GCC 4.9.0 has no problem deducing the return type:
auto fib = make_YCombinator([](auto self, int n) { if (n < 2) return 1; return self(n - 1) + self(n - 2); });
To pin this down just a bit further, here is a quote from the draft C++14 standard on return type deduction [7.1.6.4.11]:
If the type of an entity with an undeduced placeholder type is needed
to determine the type of an expression, the program is ill-formed.
Once a return statement has been seen in a function, however, the
return type deduced from that statement can be used in the rest of the
function, including in other return statements. [ Example:
auto n = n; // error, n’s type is unknown
auto f();
void g() { &f; } // error, f’s return type is unknown
auto sum(int i) {
if (i == 1)
return i; // sum’s return type is int
else
return sum(i-1)+i; // OK, sum’s return type has been deduced
}
—end example ]
It's a really hacky approach, and has severe limitations, but here it goes:
First, we need a class that pretends to support every possible operation (as far as possible), such as the fake_anything class. Note that this isn't perfect since at a minimum . and :: won't work. To fake a functor, we give it a function call operator:
template<class... Ts> fake_anything operator()(Ts&&...) const;
Knowing that the lambda has only one operator(), and that operator() has only one template parameter allows us to extract its signature with decltype(&T::operator()<fake_anything>).
For this to work, the lambda's return type must be explicitly specified; it can't use deduction, since otherwise the deduced return types will probably conflict.
Finally we can obtain the other arguments to the lambda and the return type using the standard partial specialization approach:
template<class T>
struct extract_signature;
template<class T, class R, class FA, class...Args>
struct extract_signature<R (T::*)(FA, Args...)> {
static_assert(std::is_same<fake_anything, std::decay_t<FA>>::value, "Unexpected signature");
using type = std::function<R(Args...)>;
};
template<class T, class R, class FA, class...Args>
struct extract_signature<R (T::*)(FA, Args...) const> {
static_assert(std::is_same<fake_anything, std::decay_t<FA>>::value, "Unexpected signature");
using type = std::function<R(Args...)>;
};
// other cv- and ref-qualifier versions omitted - not relevant to lambdas
// we can also static_assert that none of Args is fake_anything, or reference to it, etc.
And add an alias template to hide all the ugliness of the hack:
template<class T>
using signature_t = typename extract_signature<decltype(&T::template operator()<fake_anything>)>::type;
And finally we can check that
static_assert(std::is_same<signature_t<decltype(fib)>,
std::function<int(int)>>::value, "Oops");
Demo.
The limitations:
The return type of operator() must be explicitly specified. You cannot use automatic return type deduction, unless all of the return statements return the same type regardless of the return type of the functor.
The faking is very imperfect.
This works for operator() of a particular form only: template<class T> R operator()(T, argument-types...) with or without const, where the first parameter is T or a reference to possibly cv-qualified T.

Capture template parameter of variadic templated arguments

I have the following (incomplete, not-working) definition:
template<typename T, std::function<Args(Context&)>... Funcs>
struct constructor
{
T construct(Context& ctx)
{
return T(Funcs(ctx)...);
}
};
What I want is a templated class - the first argument is the constructed type and all following are functions to be called, the user templates with std::functions that are then called to produce the values for the constructor of type T.
I don't see a possibility to make this code work, let beside capturing the return types of the functions. I want the user to use it like this:
std::function<int(Context&)> ind = [](Context&) {return 2;};
Constructor<int, ind> c;
// c.construct(...) returns 2 by calling the constructor int(int) with argument
// ind(ctx) - which returns 2.
This might be roughly what you're looking for. Keep in mind that a std::function can't be a template parameter.
template <typename R> using Generator = std::function<R (Context&)>;
template <typename T, typename Generators, std::size_t... Is>
T constructImpl(Context& ctx, const Generators& generators,
std::index_sequence<Is...>) {
return T(std::get<Is>(generators)(ctx)...);
}
template <typename T, typename... Args>
class Constructor {
std::tuple<Generator<Args>...> generators;
public:
Constructor(Generator<Args>... generators)
: generators(std::move(generators)...)
{}
T construct(Context& ctx) {
return constructImpl<T>(ctx, generators,
std::index_sequence_for<Args...>());
}
};
Usage:
Constructor<int, int> c([](Context&) { return 2; });
int i = c.construct(context);
assert(i == 2);
Types cannot depend on run time data.
Calling std::function<X(Y)> requires run time data. So your type cannot depend on std::function<X(Y)>, so the type cannot be used as a template parameter.
Now, it can depend on a pointer to a global object: that is interestingly enough not run time state as far as C++ is concerned.
As such, your design is fundamentally flawed.
If you want a function such that it returns 2, this works:
template<class...ignored>
struct Constructor {
template<class... also_ignored>
Constructor(also_ignored&&...) {}
template<class... also_ignored>
int construct(also_ignored&&...) { return 2; }
};
this will pass the unit tests described in your OP, with the exception that you cannot pass ind to Constructor as it is not legal. However, dropping it from the type signature doesn't matter.
If you want more power, we could do this:
template<class T, class... Functors>
struct Constructor {
T construct( Context& ctx ) {
return T( Functors{}( ctx )... );
}
};
in this case you need stateless function objects:
struct ind { int operator()(Context&)const{return 2;} };
much like how std::map requires stateless comparison objects.
If your function objects require state, then you need to store a copy of them for Constructor to access (possibly within Constructor), and you might need the tuple and indexes trick to store them. ("indexes trick" is a helpful google)
I think your Construct can just be a function:
template <typename T, typename... Funcs>
T construct(Context& ctx, Funcs... funcs) {
return T(funcs(ctx)...);
}
Whose usage could be in your example could be:
int x = construct<int>(ctx, [](Context& ) { return 2; });