c++ - 断言被调用以返回 & 的函数的签名(引用)

标签 c++ debugging pass-by-reference c++14 assert

是否可以断言我调用以通过引用返回的函数类型?

断言预计只在编译时发生(但不是必需的)。

它对调试很有用。

例子

我有一个简单的 std::vector<T>封装器如下:-

template<class T> class CustomArray{
    //..... some datastructure ...
    T& get(int index) { ... }
}

某些游戏/业务逻辑可能会使用此类,例如

CustomArray<CreditCard> array ;
//... do some business logic
CreditCard& c= array.get(0);
c.pinNumber = 1403; //modification

pinNumber的修改影响了CustomArray中的值,很好。

如果我团队中有人想使用他自己的数据结构并编辑我的代码,例如

HisCustomArray<CreditCard> array ;
//replace the line : CustomArray<CreditCard> array 

我想要一种自动的方法来确保 HisCustomArray::get(int) 始终返回 T& 而不是 T,否则该行将被断开。

 c.pinNumber = 1403;

我希望得到类似于:

CustomArray<CreditCard> array ;
assertReturn_JUST_DUMMY(   array::get(int)  , CreditCard& ); //possible format
//.... other business logic ....

最佳答案

您可以使用 static_assertstd::is_reference 来获取您要查找的内容。

例子:

#include <type_traits>

template<class T> class CustomArray{
   public:
    T& get(int index) {return data;}
    T data;
};

template<class T> class HisCustomArray{
   public:
    T get(int index) {return data;}
    T data;
};

struct CreditCard {};

int main()
{
   CustomArray<CreditCard> array1;
   static_assert(std::is_reference<decltype(array1.get(0))>::value,
                 "Need a reference returning function.");
   CreditCard& c1 = array1.get(0);

   HisCustomArray<CreditCard> array2;
   static_assert(std::is_reference<decltype(array2.get(0))>::value,
                 "Need a reference returning function.");
}

编译器在编译时对 array2 进行断言。

来自 g++ 4.8.4 的错误信息:

socc.cc: In function ‘int main()’:
socc.cc:24:4: error: static assertion failed: Need a reference returning function.
    static_assert(std::is_reference<decltype(array2.get(0))>::value, "Need a reference returning function.");

关于c++ - 断言被调用以返回 & 的函数的签名(引用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37650099/

相关文章:

C++ 升压 ASIO : how to read/write with a timeout?

c++ - 错误,* 的运算符必须是指针

css调试渲染前后不一样

c++ - qt 应用程序崩溃但不容易重现,我已经捕获了转储堆栈以及如何通过堆栈查找源代码

java - 仅将 ArrayList 作为值而不是引用传递

java - 使用数组列表并创建对象

c++ - 在宏函数 C++ 中设置宏变量值

c++ - 使用ssh框架加载共享库

debugging - 雷达 2 : how to pass parameters to debugee?

C# 通过引用 C++ ActiveX 控件传递 int 和字符串 : type mismatch