【问题标题】:Printing types including decorations, template metaprogramming, constexpr, what to use?打印类型包括装饰、模板元编程、constexpr,用什么?
【发布时间】:2017-01-07 21:24:26
【问题描述】:

我有一个像这样专门用于函数的 Trait:

template <class Ret, class...Args>
struct FunctionTraits<Ret (*)(Args...)> {
   using ReturnType = Ret;

   template <std::size_t>
   using Parameter = std::tuple_element_t<std::tuple<Args...>>;
};

现在我想在不丢失装饰器的情况下打印函数的签名。

为此,我实现了这样的元函数:

template <class T>
struct GetTypeInfoString {};

它专门用于每种未修饰的类型,但我也想打印修饰的类型。我是这样使用它的:

extern constexpr auto intstr = makeStringLiteral("int");

template <>
struct GetTypeInfoString<int> {
   static constexprt auto & value = intstr;
};

现在我已经有了基本信息,我想实现一个 constexpr 函数:

template <class T>
constexpr const char * getTypeInfo() {
    //Something here...
}

我的目标是打印带有装饰的字体,而不仅仅是基本字体。即:int const * [][3]等……

【问题讨论】:

  • 您是在使用它向用户打印信息还是诊断模板问题?
  • 我有一个描述 API 的表,并生成所有元数据。我想打印完整的签名和其他数据。我正在实现一个小型可执行文件,可以查询 API 的参数和其他内容。

标签: c++ metaprogramming c++14 constexpr typeinfo


【解决方案1】:

调整:花了几个小时,但无论如何

#include <iostream>
#include <string>
#include <sstream>
#include <tuple>
#include <vector>

template <typename... T> struct type_info;

template <typename... T> struct tail_type_info;

// prints the tail of a <typename...T> type argpack
// Needed to insert commas in the appropriate places
template <typename H, typename... T>
struct tail_type_info<H,T...>
{
  std::ostream & operator()(std::ostream& o) {
    type_info<H>p;
    o << ", ";
    p(o);
    tail_type_info<T...> x;
    return x(o);
  }
};
// if the tail is empty, do nothing
template <>
struct tail_type_info<>
{
  std::ostream & operator()(std::ostream& o) {
    return o;
  }
};

// specialization for the base types
template <> struct type_info<void> {
  std::ostream& operator()(std::ostream& o) {
    o << "void";
    return o;
  }
};

template <> struct type_info<bool> {
  std::ostream& operator()(std::ostream& o) {
    o << "bool";
    return o;
  }
};

template <> struct type_info<int8_t> {
  std::ostream& operator()(std::ostream& o) {
    o << "int8_t";
    return o;
  }
};

template <> struct type_info<uint8_t> {
  std::ostream& operator()(std::ostream& o) {
    o << "uint8_t";
    return o;
  }
};

template <> struct type_info<int32_t> {
  std::ostream& operator()(std::ostream& o) {
    o << "int32_t";
    return o;
  }
};

template <> struct type_info<uint32_t> {
  std::ostream& operator()(std::ostream& o) {
    o << "uint32_t";
    return o;
  }
};

template <> struct type_info<int64_t> {
  std::ostream& operator()(std::ostream& o) {
    o << "int64_t";
    return o;
  }
};

template <> struct type_info<uint64_t> {
  std::ostream& operator()(std::ostream& o) {
    o << "uint64_t";
    return o;
  }
};

// TODO fill it in for the rest of the types (char, short, wchar_t)


// compound types (&, *, CV, [N], [])
template <typename T>
struct type_info<T*> {
  std::ostream& operator()(std::ostream& o) {
    type_info<T> p;
    p(o) << " *";
    return o;
  }
};
template <typename T>
struct type_info<T&> {
  std::ostream& operator()(std::ostream& o) {
    type_info<T> p;
    p(o) << " &";
    return o;
  }
};
template <typename T>
struct type_info<const T> {
  std::ostream& operator()(std::ostream& o) {
    type_info<T>p;
    p(o) << " const";
    return o;
  }
};

template <typename T>
struct type_info<volatile T> {
  std::ostream& operator()(std::ostream& o) {
    type_info<T>p;
    p(o) << " volatile";
    return o;
  }
};

template <typename T, size_t N>
struct type_info<T[N]> {
  std::ostream& operator()(std::ostream& o) {
    type_info<T>p;
    p(o) << "[" << N << "]";
    return o;
  }
};

template <typename T>
struct type_info<T[]> {
  std::ostream& operator()(std::ostream& o) {
    type_info<T>p;
    p(o) << "[]";
    return o;
  }
};

// specialization for std::containers
template <typename T>
struct type_info<std::vector<T>> {
  std::ostream& operator()(std::ostream& o) {
    type_info<T>p;
    o << "std::vector<";
    p(o);
    return o << ">";
  }
};
// TODO define specializations for other containers as necessary

// specialization for std::tuple as an example of variadic template types
template <typename H, typename... T>
struct type_info<std::tuple<H, T...>> {
  std::ostream& operator()(std::ostream& o) {
    type_info<H>p;
    tail_type_info<T...>tailp;
    o << "std::tuple<";
    p(o);
    tailp(o);
    return o << ">";
  }
};

template <typename H>
struct type_info<std::tuple<H>> {
  std::ostream& operator()(std::ostream& o) {
    type_info<H>p;
    o << "std::tuple<";
    p(o);
    return o << ">";
  }
};

template <>
struct type_info<std::tuple<>> {
  std::ostream& operator()(std::ostream& o) {
    o << "std::tuple<";
    return o << ">";
  }
};


// specialization for functions
// function with no args
template <typename R>
struct type_info<R(*)(void)>
{
  std::ostream& operator()(std::ostream& o) {
    type_info<R>p;
    p(o) << " (*)(void)";
    return o;
  }
};

// function with 1 arg
template <typename R, typename A0>
struct type_info<R(*)(A0)>
{
  std::ostream& operator()(std::ostream& o) {
    type_info<R>p;
    type_info<A0>a;
    p(o) << " (*)(";
    a(o) << ")";
    return o;
  }
};

// function with multiple args
template <typename R, typename Ah, typename... At>
struct type_info<R(*)(Ah, At...)>
{
  std::ostream& operator()(std::ostream& o) {
    type_info<R>p;
    type_info<Ah>a;
    tail_type_info<At...>a_tail;
    p(o) << " (*)(";
    a(o);
    a_tail(o);
    o << ")";
    return o;
  }
};



template<typename... T> std::ostream& operator << (std::ostream& o, type_info<T...>& v) {
  return v(o);
}

template <typename R, typename... A>
std::string FunctionSignatureStr(R(A...)&) {
  std::stringstream dest;
  type_info<R(*)(A...)> funcTrace;
  funcTrace(dest);
  return dest.str();
}

std::vector<long> dummyFunc(std::tuple<const long*[4], volatile bool& > const&) {
  return std::vector<long>();
}

int main() {
  std::cout << FunctionSignatureStr(dummyFunc) << std::endl;

  type_info<std::vector<long>(*)(std::tuple<const long*, volatile bool&> const&)> d;
  std::cout << d << std::endl;
}

【讨论】:

    【解决方案2】:

    对此没有标准的 C++ 库函数,但大多数编译器确实提供了一些解组签名的方法。

    对于 gcc,这看起来像这样。

    #include <cxxabi.h>
    #include <iostream>
    
    template <class T>
    constexpr std::string getTypeInfo() {
    
        int status=0;
        char *t=abi::__cxa_demangle(typeid(T).name(), 0, 0, &status);
    
        std::string s=t;
        free(t);
        return s;
    }
    
    
    template<class C, class T>
    void foobar(C c, T t)
    {
    }
    
    class Z {};
    
    int main()
    {
        std::cout << getTypeInfo<int>() << std::endl;
        std::cout << getTypeInfo<Z *[5]>() << std::endl;
    
        auto *p= &foobar<int, char>;
    
        std::cout << getTypeInfo<decltype(p)>() << std::endl;
    }
    

    输出:

    int
    Z* [5]
    void (*)(int, char)
    

    【讨论】:

    • 不幸的是,abi 将失去 CV 预选赛
    • "getTypeInfo()" 返回 "int volatile*"。
    • 我需要一个便携式解决方案。
    • 那么答案是:没有便携的解决方案。
    • @SamVarshavchik 是的,有。但是,这不是一个简单的方法,要考虑到需要使用 argpack 模板获取函数的类型。
    【解决方案3】:

    问题基本上是如何得到这个:

    int main()
    {
        std::cout << TypeInfo<const int>::value() << std::endl;
        std::cout << TypeInfo<const int&>::value() << std::endl;
        std::cout << TypeInfo<int&&>::value() << std::endl;
        std::cout << TypeInfo<const volatile int&>::value() << std::endl;
    }
    

    制作这个:

    const int
    const int&
    int&&
    const volatile int&
    

    以 constexpr 方式。

    答案:

    #include <iostream>
    #include <tuple>
    
    template <class T>
    struct TypeInfo;
    
    template<std::size_t N>
    struct immutable_string
    {
        constexpr immutable_string(const char (&s)[N])
        : _data {}
        {
            for (std::size_t i = 0 ; i < N ; ++i)
                _data[i] = s[i];
        }
    
        constexpr immutable_string()
        : _data {}
        {
        }
    
        constexpr char& operator[](std::size_t i) { return _data[i]; }
        constexpr const char& operator[](std::size_t i) const { return _data[i]; }
    
        using ref = const char (&)[N];
    
        constexpr ref data() const { return _data; }
        static constexpr std::size_t size() { return N-1; }
    
        char _data[N];
    };
    
    template<std::size_t N>
    std::ostream& operator<<(std::ostream& os, immutable_string<N> s)
    {
        return os.write(s.data(), s.size());
    }
    
    template<std::size_t LN, std::size_t RN>
    constexpr auto operator+(immutable_string<LN> l, immutable_string<RN> r)
    {
        constexpr std::size_t len = LN + RN - 2;
        immutable_string<len + 1> result;
        std::size_t i = 0;
        for ( ; i < (LN-1) ; ++i)
        {
            result[i] = l[i];
        }
        for (auto j = 0 ; j < (RN-1) ; ++j)
        {
            result[i + j] = r[j];
        }
    
        return result;
    }
    
    template<std::size_t N>
    constexpr auto literal(const char (&s)[N])
    {
        return immutable_string<N>(s);
    }
    
    template <>
    struct TypeInfo<int> {
        static constexpr auto value() { return literal("int"); }
    };
    
    template<class T>
    struct TypeInfo<const T>
    {
        static constexpr auto value() { return literal("const ") + TypeInfo<T>::value(); }
    };
    
    template<class T>
    struct TypeInfo<volatile T>
    {
        static constexpr auto value() { return literal("volatile ") + TypeInfo<T>::value(); }
    };
    
    template<class T>
    struct TypeInfo<const volatile T>
    {
        static constexpr auto value() { return literal("const volatile ") + TypeInfo<T>::value(); }
    };
    
    template<class T>
    struct TypeInfo<T&>
    {
        static constexpr auto value() { return TypeInfo<T>::value() + literal("&"); }
    };
    
    template<class T>
    struct TypeInfo<T&&>
    {
        static constexpr auto value() { return TypeInfo<T>::value() + literal("&&"); }
    };
    
    
    int main()
    {
        std::cout << TypeInfo<const int>::value() << std::endl;
        std::cout << TypeInfo<const int&>::value() << std::endl;
        std::cout << TypeInfo<int&&>::value() << std::endl;
        std::cout << TypeInfo<const volatile int&>::value() << std::endl;
    }
    

    产生输出:

    const int
    const int&
    int&&
    const volatile int&
    

    更新:

    一个更完整/更可靠的例子:

    #include <iostream>
    
    template <class T>
    struct TypeInfo;
    
    
    template<std::size_t N>
    struct immutable_string
    {
        constexpr immutable_string(const char (&s)[N])
        : _data {}
        {
            for (std::size_t i = 0 ; i < N ; ++i)
                _data[i] = s[i];
        }
    
        constexpr immutable_string()
        : _data {}
        {
        }
    
        constexpr char& operator[](std::size_t i) { return _data[i]; }
        constexpr const char& operator[](std::size_t i) const { return _data[i]; }
    
        using ref = const char (&)[N];
    
        constexpr ref data() const { return _data; }
        static constexpr std::size_t size() { return N-1; }
    
        char _data[N];
    };
    
    template<std::size_t N>
    std::ostream& operator<<(std::ostream& os, immutable_string<N> s)
    {
        return os.write(s.data(), s.size());
    }
    
    template<std::size_t LN, std::size_t RN>
    constexpr auto operator+(immutable_string<LN> l, immutable_string<RN> r)
    {
        constexpr std::size_t len = LN + RN - 2;
        immutable_string<len + 1> result;
        std::size_t i = 0;
        for ( ; i < (LN-1) ; ++i)
        {
            result[i] = l[i];
        }
        for (auto j = 0 ; j < (RN-1) ; ++j)
        {
            result[i + j] = r[j];
        }
    
        return result;
    }
    
    template<std::size_t N>
    constexpr auto literal(const char (&s)[N])
    {
        return immutable_string<N>(s);
    }
    
    template <>
    struct TypeInfo<int> {
        static constexpr auto value() { return literal("int"); }
    };
    
    template<class T>
    struct TypeInfo<const T>
    {
        static constexpr auto value() { return TypeInfo<T>::value() + literal(" const"); }
    };
    
    template<class T>
    struct TypeInfo<volatile T>
    {
        static constexpr auto value() { return TypeInfo<T>::value() + literal(" volatile"); }
    };
    
    template<class T>
    struct TypeInfo<const volatile T>
    {
        static constexpr auto value() { return TypeInfo<T>::value() + literal(" const volatile"); }
    };
    
    template<class T>
    struct TypeInfo<T&>
    {
        static constexpr auto value() { return TypeInfo<T>::value() + literal("&"); }
    };
    
    template<class T>
    struct TypeInfo<T&&>
    {
        static constexpr auto value() { return TypeInfo<T>::value() + literal("&&"); }
    };
    
    template<class T>
    struct TypeInfo<T*>
    {
        static constexpr auto value() { return TypeInfo<T>::value() + literal("*"); }
    };
    
    
    int main()
    {
        std::cout << TypeInfo<const int>::value() << std::endl;
        std::cout << TypeInfo<const int&>::value() << std::endl;
        std::cout << TypeInfo<int&&>::value() << std::endl;
        std::cout << TypeInfo<const volatile int&>::value() << std::endl;
        std::cout << TypeInfo<const volatile int* const* volatile * const volatile **const *&>::value() << std::endl;
    }
    

    预期输出:

    int const
    int const&
    int&&
    int const volatile&
    int const volatile* const* volatile* const volatile** const*&
    

    【讨论】:

    • 好的,我被卡住的关键点...静态 constexpr 自动值变量...使它成为一个函数并且它工作!好点子。非常感谢。我会接受这个回复。
    • immutable_string 又名std::string_view 甚至std::array
    • @black constexpr std::array 在 c++17 之前是不可变的。 string_view 不能进行编译时连接,所以不幸的是两者都不合适。
    【解决方案4】:

    用 gnu 扩展文字字符串,你可以这样做

    template <typename Char, Char...Cs>
    struct LString
    {
        static constexpr Char value[] = {Cs..., 0};
    };
    
    template <typename Char, Char...Cs> constexpr Char LString<Char, Cs...>::value[];
    
    // string literal operator templates are a GNU extension
    template <typename Char, Char...Cs>
    constexpr LString<Char, Cs...> operator ""_ls()
    {
        return {};
    }
    
    template <typename Char, Char...Lhs, Char...Rhs>
    constexpr LString<Char, Lhs..., Rhs...>
    operator + (const LString<Char, Lhs...>&, const LString<Char, Rhs...>&)
    {
        return {};
    }
    
    template <typename Stream, typename Char, Char...Cs>
    Stream& operator << (Stream& s, const LString<Char, Cs...>&ls)
    {
       return s << ls.value;
    }
    

    然后是你的类型和专长

    template <typename T> struct TypeInfo;
    
    template <> struct TypeInfo<int> { static constexpr auto value = "int"_ls; };
    
    template<class T> struct TypeInfo<const T>
    {
        static constexpr auto value = "const "_ls + TypeInfo<T>::value;
    };
    
    // ...
    

    Demo

    【讨论】:

    • 很遗憾它没有成为标准。真的很有用。
    猜你喜欢
    • 2015-08-30
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2018-12-05
    • 2012-09-29
    相关资源
    最近更新 更多