'How to invoke a templated static class method having tuple input in a constexpr way
How can a static constexpr class::method (int i1, int i2, int i3) be invoked, having input data available as tuple<int, int, int> in a constexpr way.
The default approach is using std::apply to apply each tuple element as argument to a function.
A minimal example to visualize, what I try to achieve looks like:
struct a {
template <typename T>
static constexpr void test(int i1, int i2, int i3) {
// ...
}
};
struct b : a {};
struct c {};
template <typename T>
struct test_functor {
constexpr test_functor_t() {} // just for testing to express constexpr desire
constexpr void operator()(auto... args) {
T::test<c>(args...);
}
};
constexpr std::tuple<int, int, int> tupl{ 1,2,3 };
constexpr test_functor<b> f;
std::apply(f, tupl);
this works at runtime, but fails to compile constexpr. How can this be implemented?
Solution 1:[1]
Working test_functor:
template <typename T>
struct test_functor {
constexpr void operator()(auto... args) const {
T::template test<c>(args...);
}
};
The problems:
- Your constructor was misnamed, and ultimately unnecessary – without a constructor your type is an aggregate and can be
constexpr-constructed just fine. - Your
operator()was notconst– the primary problem, as you can't invoke a non-constmember on aconstexprobject. - Missing
templatekeyword when invokingT::test– see this FAQ answer for a good explanation of dependent names.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
