Yes, it is possible. The most tricky part is that you ask for a solution which returns a const char*
(rather than something which owns the data).
As you notice in your example, the const char*
needs a buffer to point to. This is tricky because constexpr
functions are currently (C++17) not allowed to have a static constexpr char buffer[size]{/* whatever*/};
. Instead, you can use a static data member of a templated helper class.
The following is a complete demonstration which I have tested with both clang 6.0.1 and GCC 8.1.1 using -std=c++14
.
#include <cassert>
#include <cstddef>
#include <iostream>
template<class T>
constexpr const char* getName();
template<>
constexpr const char* getName<int>() {
return "int";
}
template<std::size_t N>
constexpr const char* getNumericString();
template<>
constexpr const char* getNumericString<16>() {
return "16";
}
constexpr std::size_t getStrLen(const char* str) {
std::size_t ret = 0;
while(str[ret] != '\0') ret++;
return ret;
}
static_assert(getStrLen("") == 0, "");
static_assert(getStrLen("ab") == 2, "");
static_assert(getStrLen("4\0\0aaa") == 1, "");
struct Wrapper {
const char* str;
constexpr auto begin() const { return str; }
constexpr auto end() const {
auto it = str;
while(*it != '\0') ++it;
return it;
}
};
template<class T, std::size_t size>
class Array {
private:
T data_[size]{};
public:
constexpr T& operator[](std::size_t i) { return data_[i]; }
constexpr const T& operator[](std::size_t i) const { return data_[i]; }
constexpr const T* data() const { return data_; }
};
template<std::size_t buffer_size, class... Args>
constexpr Array<char, buffer_size> cat(Args... args) {
Array<char, buffer_size> ret{};
std::size_t i = 0;
for(auto arg : {Wrapper{args}...}) {
for(char c : arg) ret[i++] = c;
}
return ret;
}
template<class T, std::size_t N>
struct StaticDataForConstexprFunction {
static constexpr const char* name = getName<T>();
static constexpr const char* length = getNumericString<N>();
static constexpr std::size_t size = getStrLen(name) + getStrLen(length) + 10;
using Buffer = Array<char, size>;
static constexpr Buffer buffer = cat<size>(name, "[", length, "]\0");
};
template<class T, std::size_t N>
constexpr typename StaticDataForConstexprFunction<T, N>::Buffer StaticDataForConstexprFunction<T, N>::buffer;
template<class T, std::size_t N>
constexpr const char* getName(T (&)[N]) {
return StaticDataForConstexprFunction<T, N>::buffer.data();
}
int main() {
int foobar[16];
constexpr auto res = getName(foobar);
std::cout << res << std::endl;
}