C++ 类型名称作为 static_assert 中错误报告的文字字符串

标签 c++ templates types static-assert

我正在使用这个宏来确保某些类型对齐:

#define TYPE_EQ(t1, t2) static_assert(std::is_same<t1, t2>::value)

忍受我做作的例子:

#include <iostream>

#define TYPE_EQ(t1, t2) static_assert(std::is_same<t1, t2>::value)

class Fn1 {
 public:
    int operator()(const char s) {
        return s == 'a' ? 0 : 1;
    }
    typedef char Domain;
    typedef int Codomain;
};

class Fn2 {
 public:
    char operator()(const bool s) {
        return s ? 'a' : 'b';
    }
    typedef bool Domain;
    typedef char Codomain;
};

template<typename F1, typename F2>
class Compose {
 public:
    Compose () {
        TYPE_EQ(typename F1::Domain, typename F2::Codomain);
    }

    typedef typename F1::Codomain Codomain;
    typedef typename F2::Domain Domain;

    Codomain operator()(const Domain& x) {
        F1 f1;
        F2 f2;
        return f1(f2(x));
    }
};

int main() {
    std::cout << Compose<Fn2, Fn1>()(true) << std::endl;
    return 0;
}

这里我得到的只是error: static_assert failed,但我想知道什么是类型不匹配。为此,我认为我需要在编译时使用类型的字符串表示形式,例如我可以:

#define TYPE_EQ(t1, t2) static_assert(std::is_same<t1, t2>::value, \
                                      type_str(t1) " != " type_str(t2))

编辑:我认为编译器不会反对这一点。我没有 gcc ATM 但 clang sais:

g++ -Wall -std=c++17 test.cc -o test && ./test
test.cc:27:9: error: static_assert failed
        TYPE_EQ(typename F1::Domain, typename F2::Codomain);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.cc:3:25: note: expanded from macro 'TYPE_EQ'
#define TYPE_EQ(t1, t2) static_assert(std::is_same<t1, t2>::value)
                        ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.cc:41:18: note: in instantiation of member function 'Compose<Fn2, Fn1>::Compose'
      requested here
    std::cout << Compose<Fn2, Fn1>()(true) << std::endl;
                 ^
1 error generated.

要澄清真正的问题要复杂得多,所以我想要最终类型,即intboo,而不是类型名。

最佳答案

为调试检索类型的经典方法是使用不完整的类型:

template <typename> struct Debug;

Debug<Fn1::Domain> d;

产生类似于以下的错误:

error: aggregate 'Debug<char> d' has incomplete type and cannot be defined
Debug<Fn1::Domain> d;

关于C++ 类型名称作为 static_assert 中错误报告的文字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50047283/

相关文章:

c++ - 哪个 Windows API 捕获屏幕比 Bitblt 或任何其他镜像驱动程序更快?

c++ - 使用 Emscripten 构建静态或共享的 boost 库

c++ - Variadic 模板参数总是必须放在最后吗?

c++ - 无法将字符串传递给 CreateThread 接收器

c++ - cpp文件的sublime 3文本和制表符大小

c++ - 使用 decltype 推导返回类型时避免代码大量重复的最佳方法

C++如何在泛型编程中声明一个自定义数组

c++ - 如何检查是否定义了固定宽度整数

haskell - 'Either e` 包中 `Failure` 的 "failure"实例存在问题

arrays - Select-Object -Unique返回String而不是String数组