c++ 在编译时打印模板类型

iih3973s  于 11个月前  发布在  其他
关注(0)|答案(7)|浏览(153)

当在C++中创建模板函数时,是否有一种简单的方法将模板的类型表示为字符串?我有一个简单的测试用例来展示我正在尝试做的事情(注意,所示代码无法编译):

#include <stdio.h>
template <typename type>
type print(type *addr) 
{
  printf("type is: %s",type);
}

int main()
{
  int a;
  print(&a);
}

// Would like to print something like:
// type is: int

字符串
我认为在编译时,当函数被示例化时,类型应该是可用的,但是我对模板不太熟悉,我还没有看到一种方法可以将类型作为字符串获取。
我想这样做的原因是为了一些printf类型的调试。我有多个线程在运行,用gdb单步执行会改变程序的行为。所以对于一些事情,我想转储有关哪些函数正在执行的信息。这并不太重要,所以如果解决方案过于复杂,我会跳过将此信息添加到日志函数中。但是如果有一种简单的方法来做到这一点,它将是有用的信息要有。

kb5ga3dv

kb5ga3dv1#

获取一个有用的编译时名称:
假设你有一个名为'T'的未知类型。你可以通过糟糕地使用它来让编译器打印它的类型。例如:

typedef typename T::something_made_up X;

字符串
错误消息如下:

error: no type named 'something_made_up' in 'Wt::Dbo::ptr<trader::model::Candle>'


“in”后面的位显示类型。(仅用clang测试)。
其他触发方式:

bool x = T::nothing;   // error: no member named 'nothing' in 'Wt::Dbo::ptr<trader::model::Candle>'
using X = typename T::nothing;  // error: no type named 'nothing' in 'Wt::Dbo::ptr<trader::model::Candle>'


在C++11中,你可能已经有了一个对象,并使用decltype来获取它的类型,所以你也可以运行:

auto obj = creatSomeObject();
bool x = decltype(obj)::nothing; // (Where nothing is not a real member).

lymgl2op

lymgl2op2#

__PRETTY_FUNCTION__应该可以解决您的问题(至少在运行时)
下面程序的输出是:

asfdasdfasdf test<type>::test() [with type = int]
asfdasdfasdf test<type>::test() [with type = int]
asfdasdfasdf test<type>::test() [with type = int]
asfdasdfasdf test<type>::test() [with type = int]
asfdasdfasdf test<type>::test() [with type = int]
asfdasdfasdf test<type>::test() [with type = int]
asfdasdfasdf void tempFunction() [with type = bool]
asfdasdfasdf void tempFunction() [with type = bool]
asfdasdfasdf void tempFunction() [with type = bool]
asfdasdfasdf void tempFunction() [with type = bool]
asfdasdfasdf void tempFunction() [with type = bool]
asfdasdfasdf void tempFunction() [with type = bool]
!!!Hello World!!!

字符串
如果你真的,真的,需要将类型字符串作为字符串,你可以破解这个(使用snprintf而不是printf),并拉取'='之后和''之前的子字符串。

#include <iostream>
using namespace std;

template<typename type>
class test
{
public:
test()
{
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
}
};

template<typename type>
void tempFunction()
{
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
    printf("asfdasdfasdf %s\n", __PRETTY_FUNCTION__);
}

int main() {
    test<int> test;

    tempFunction<bool>();
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}

z8dt9xmd

z8dt9xmd3#

另一个编译时解决方案,类似于matiu提供的解决方案,但可能更具描述性,是使用 Package 在一个小助手函数中的static_assert

#include <utility>

template <typename T>
struct always_false : std::false_type { };

template <typename T>
constexpr bool always_false_v = always_false<T>::value;

template <typename T>
void print_type_in_compilation_error(T&&)
{
    static_assert(always_false_v<T>,
                  "Compilation failed because you wanted to know the type; see below:");
}

个字符
上面会给予你一个很好的错误消息(在MSVC和Clang中测试过),就像在另一个答案中一样,但在我看来,代码更容易理解。
注意:原始答案中的代码格式不正确,所以我稍微修改了一下代码。always_false的功劳归于this答案。

s4chpxco

s4chpxco4#

既然你说你需要它用于调试目的,也许运行时解决方案也是可以接受的。你已经把它标记为g++,所以你不想符合标准。
这意味着:

#include <cxxabi.h> // the libstdc++ used by g++ does contain this header

template <typename type>
void print(const type *addr) // you wanted a pointer
{
  char * name = abi::__cxa_demangle(typeid(*addr).name(), 0, 0, NULL);
  printf("type is: %s\n", name);
  free(name);
}
     
print(new unsigned long);    // prints "type is: unsigned long"
print(new std::vector<int>); // prints "type is: std::vector<int, std::allocator<int> >"

字符串
编辑:修正了内存泄漏。感谢杰西。

6yoyoihd

6yoyoihd5#

有Boost.TypeIndex库。
详情请参见boost::typeindex::type_id。
它非常易于使用,跨平台,是真实的编译型解决方案。即使没有RTTI可用,它也能正常工作。此外,大多数编译器都支持。

4jb9z9bj

4jb9z9bj6#

你可以使用C++20的concept s来定义一个任何类型都不能满足的约束。在模板参数上使用这个约束并示例化模板将导致编译器失败并打印出推导出的类型。

void print_typename (auto) requires false {}
// Equivalent to
//   template<typename T>
//   concept unsatisfiable_c = false;
//   
//   template<unsatisfiable_c T>
//   void print_typename (T) {}

int main (int, char**) {
    int foo = 73;
    print_typename(foo);
    // error: no matching function for call to 'print_typename'
    // note: candidate template ignored: constraints not satisfied [with auto:1 = int]
    //                                                                            ^^^

    return 0;
}

字符串
如果你的T更复杂,例如T=std::vector<std::pair<key_t, value_t>>T=void (*)(U, V const&),你想具体找出key_tV,你可以这样做:

template<typename T>
concept unsatisfiable_c = false;

template<unsatisfiable_c key_t, typename value_t>
void print_key_t (std::vector<std::pair<key_t, value_t>>) {}

template<typename U, unsatisfiable_c V>
void print_V (void (*)(U, V const&)) {}

void foo (double, long double const&) {}

int main (int, char**) {
    std::vector<std::pair<long, char>> bar;

    print_key_t(bar);
    // error: no matching function for call to 'print_key_t'
    // note: candidate template ignored: constraints not satisfied [with key_t = long, value_t = char]

    print_V(&foo);
    // error: no matching function for call to 'print_V'
    // note: candidate template ignored: constraints not satisfied [with U = double, V = long double]

    return 0;
}

rslzwgfq

rslzwgfq7#

如果你不在乎语句会破坏编译,最简单的方法是:

static_assert( 1== T::not_existed_member_name, "print the T type when compile" )

字符串
没有办法在不破坏编译的情况下打印类型。(当然你可以触发一个警告,而不是这里的错误)

相关问题