相关疑难解决方法(0)

是否可以在编译时打印出C++类的大小?

是否有可能在编译时确定C++类的大小?

我似乎记得模板元编程方法,但我可能会弄错...


抱歉没有更清楚 - 我希望在构建输出窗口中打印大小

c++

61
推荐指数
3
解决办法
2万
查看次数

在C++中编译和打印在编译时的阶乘

template<unsigned int n>
struct Factorial {
    enum { value = n * Factorial<n-1>::value};
};

template<>
struct Factorial<0> {
    enum {value = 1};
};

int main() {
    std::cout << Factorial<5>::value;
    std::cout << Factorial<10>::value;
}
Run Code Online (Sandbox Code Playgroud)

上面的程序在编译期间计算阶乘值.我想在编译时打印阶乘值,而不是在运行时使用cout打印.我们怎样才能在编译时打印阶乘值?

我正在使用VS2009.

谢谢!

c++ templates compile-time

23
推荐指数
2
解决办法
7804
查看次数

在static_assert()中在编译时显示整数

这是我正在尝试做的简化版本

enum First
{
    a,
    b,
    c,
    nbElementFirstEnum,
};
enum Second
{
    a,
    b,
    c,
    nbElementSecondEnum,
};

static_assert(
    First::nbElementFirstEnum == Second::nbElementSecondEnum,
    "Not the same number of element in the enums.");
/*static_assert(  
    First::nbElementFirstEnum == Second::nbElementSecondEnum, 
    "Not the same number of element in the enums." + First::nbElementFirstEnum + " " + Second::nbElementSecondEnum);*/
Run Code Online (Sandbox Code Playgroud)

但是我希望能够在断言消息中打印First :: nbElementFirstEnum和Second :: nbElementSecondEnum的值(就像在注释版本中显然不起作用).我尝试使用"#"进行宏连接.我还尝试使用可变参数模板,使用%10检索每个数字并将"0"字符添加到检索到的值,但我得到的只是constexpr char [].

所以我的问题是如何让我的枚举值以字符串文字打印.

可能重复:

C++ 11 static_assert:参数化错误消息

在static_assert输出中集成类型名称?

最有趣的话题是: 在编译时打印sizeof(T) 但是我不希望有警告或退出代码来知道值.

c++ macros integer static-assert c++11

11
推荐指数
3
解决办法
7400
查看次数

标签 统计

c++ ×3

c++11 ×1

compile-time ×1

integer ×1

macros ×1

static-assert ×1

templates ×1