相关疑难解决方法(0)

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

我喜欢提供有用的错误/消息,我也想为我static_assert的.问题是,它们依赖于模板参数.通常情况下,由于引发的错误,这些参数会在途中或其他参数上显示,但它们要么模糊不清,要么不分组,因此它们有意义.例:

template<class T>
struct fake_dependency{
  static bool const value = false;
};

template<class T, class Tag>
struct Foo{
  Foo(){}

  template<class OtherTag>
  Foo(Foo<T, OtherTag> const&){
    static_assert(fake_dependency<T>::value, "Cannot create Foo<T,Tag> from Foo<T,OtherTag>.");
  }
};

int main(){
    Foo<int, struct TagA> fA;
    Foo<int, struct TagB> fB(fA);
}
Run Code Online (Sandbox Code Playgroud)

MSVC上的输出:

src\main.cpp(74): error C2338: Cannot create Foo<T,Tag> from Foo<T,OtherTag>.
          src\main.cpp(84) : see reference to function template instantiation 'Foo<T,Tag>::Foo<main::TagA>(const Foo<T,main::TagA> &)' being compiled
          with
          [
              T=int,
              Tag=main::TagB
          ]
Run Code Online (Sandbox Code Playgroud)

函数模板本身提到了一个标记,下面是类模板.不太好.让我们看看海湾合作委员会的成果:

prog.cpp: In constructor 'Foo<T, Tag>::Foo(const …
Run Code Online (Sandbox Code Playgroud)

c++ templates static-assert custom-errors c++11

56
推荐指数
2
解决办法
1万
查看次数

在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++ 11 static_assert(以及其中使用的函数)

static_assert 似乎是一个非常好的功能与模板.

但是,我无法在标准库中查找函数,以便在编译时进行各种测试.

例如,我正在寻找一个函数来检查类型是否是另一个类型的子类型.boost::is_base_of但是,这项工作在std中是一个类似的功能,所以我不需要依赖boost.

基本上,是否有一个很好的源代码可以在static_assertC++ 11的标准库中使用并包含在函数列表中?

什么时候static_assert执行?我可以将它放在模板中的任何位置,并针对每个模板实例进行评估吗?它可以用来将模板参数约束为类的特定子类型吗?

c++ static-assert assertions c++11

1
推荐指数
2
解决办法
2612
查看次数