Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to print a constexpr string during compiletime?

Tags:

c++11

I'm trying to do the following (only relevant parts of code below):

template<typename ContainerType>
struct IsContainerCheck : is_container<ContainerType>
{
   static constexpr char* err_value = "Type is not a container model";
};

namespace _check_concept {
    template<typename ResultType>
    struct run {
        constexpr static int apply() {
            static_assert(false, IsContainerCheck<ResultType>::err_value)
            return 0;
        }
    };

    template<>
    struct run<true_t> {
        constexpr static int apply() {
            return 0;
        }
    };
}

This fails because the static_assert allows only literals to be printed. The same is with BOOST_STATIC_ASSERT_MSG macro.

So my question is - is there any way to output a constexpr string during compilation? If there is a gcc extension providing this functionality that would also be great.

Used compiler gcc 4.8.1

like image 648
Marcin Avatar asked Jul 18 '13 10:07

Marcin


1 Answers

GCC does not provide such a mechanism as you want. However you will not need it if you are able to refactor your code somewhat as illustrated in the following program. (I have filled in a few gaps so as to give us a compilable example):

#include <type_traits>
#include <vector>

template<typename ContainerType>
struct is_container
{
    static bool const value = false;
};

template<>
struct is_container<std::vector<int>>
{
    static bool const value = true;
};

template<typename ContainerType>
struct IsContainerCheck // : is_container<ContainerType> <- Uneccessary
{
    static_assert(is_container<ContainerType>::value, 
        "Type is not a container model");
};

namespace _check_concept {
    template<typename ResultType>
    struct run {
        constexpr static int apply() {
            return (IsContainerCheck<ResultType>(),0);
        }
    };

    // No such specialization is necessary. Delete it.
    // template<>
    // struct run<true_t> {
    //    constexpr static int apply() {
    //        return 0;
    //    }
    //};
}

using namespace _check_concept;

int main(int argc, char **argv)
{
    auto verdict0 = run<std::vector<int>>::apply();
    (void)verdict0;
    // The following line will static_assert: "Type is not a container model"
    auto verdict1 = run<float>::apply();
    (void)verdict1;
    return 0;
}

In your specialization _check_concept::struct run<true_t> I presume that true_t is not an alias or equivalent of std::true_type, but rather just a place-holder for some ResultType that is a container type. As the test program shows, no such specialization is now necessary, because IsContainerCheck<ResultType>() will static_assert, or not, depending on ResultType, in the unspecialized run<ResultType>::apply().

like image 123
Mike Kinghan Avatar answered Oct 09 '22 06:10

Mike Kinghan