Suppose I have some template class A
which takes an integer parameter:
template<int N>
struct A;
Now I would like to build a factory method which builds an A based on some evaluation of a function f
, which may or may not be constexpr. If the evaluated result is constexpr, the return value should be A<f(args...)>
. Otherwise, I want the return result to be A<0>
.
Conceptually, I want something like this:
template<class F, class... Args>
auto factory(F&& f, Args&&... args)
-> (is_result_constexpr(f(std::forward<Args>(args)...)) ? A<f(std::forward<Args>(args)...)> : A<0>)
{
// ... dispatch to appropriate helper to construct constexpr/non-constexpr versions
}
- How would I do this (is this even possible)?
- If this isn't possible in C++11, what about C++14/C++17?
As an example usage of what I want, suppose I have a constexpr function f0
:
constexpr int f0(int N)
{
return N;
}
int main()
{
auto a0 = factory(f0, 1); // should have type A<1>
int val;
std::cin >> val; // val isn't compile time known
auto a1 = factory(f0, val); // should have type A<0>
}
Aucun commentaire:
Enregistrer un commentaire