1

I have a template class with some integers as arguments. One static const integer (call it Length) of this class needs to be calculated based on the arguments. The calculation does need a loop (as far as I know) so a simple expression won't help.

static int setLength()
{
    int length = 1;
    while (length <= someTemplateArgument)
    {
        length = length << 1;
    }
    return length;
}

The returned length should be used to init Length. Lengthis used as a fixed length of an array so I need it to be constant.

Is there a solution for this issue? I know that constexp could help but I can't use C11 or later.

1
  • 1
    Of course, you can do some template-metaprogramming to get your constant right. I'm personally not really into the details of that because I think that template-metaprogramming is an atrocity that's best avoided, but it's certainly doable. Commented Dec 18, 2015 at 15:29

1 Answer 1

2

Using metaprogramming. Implementation of C++11 enable_if taken from cppreference.com

#include <iostream>

template<bool B, class T = void>
struct enable_if {};

template<class T>
struct enable_if<true, T> { typedef T type; };

template <int length, int arg, typename = void>
struct length_impl
{
    static const int value = length_impl<(length << 1), arg>::value;
};

template <int length, int arg>
struct length_impl<length, arg, typename enable_if<(length > arg)>::type>
{
    static const int value = length ;
};

template <int arg>
struct length_holder
{
    static const int value = length_impl<1, arg>::value;
};

template<int n>
struct constexpr_checker
{
    static const int value = n;
};

int main()
{
    std::cout << constexpr_checker< length_holder<20>::value >::value;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, that seems to be the correct approach here. Thanks!
Seems to be the correct solution, so +1 for that. Still, it only goes to prove what I said in the comments above: Template metaprogramming is an atrocity...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.