问题
Background
I'm writing a Windows Store App in C++ using the Windows Store Unit Test Project. While trying to figure out how to test that an exception was raised, I found Assert::ExpectedException in CppUnitTestAssert.h. Its signatures are below:
template<typename _EXPECTEDEXCEPTION, typename _RETURNTYPE> static void ExpectException(_RETURNTYPE (*func)(), const wchar_t* message = NULL, const __LineInfo* pLineInfo = NULL)
{
...
}
and
template<typename _EXPECTEDEXCEPTION, typename _FUNCTOR> static void ExpectException(_FUNCTOR functor, const wchar_t* message = NULL, const __LineInfo* pLineInfo = NULL)`
{
...
}
The Question Is:
It's been a LONG time since I coded in C++, so I'm having difficulty figuring out how to call the method correctly. I keep getting the following error:
'Microsoft::VisualStudio::CppUnitTestFramework::Assert::ExpectException' : none of the 2 overloads could convert all the argument types
I realize this may be actually be a misunderstanding of "pure" C++, but I'm not sure if C++/CX may have different rules for using function pointers that C++. Or at least what I remember the rules to be.
EDIT:
I'm attempting to use the function pointer overload, _RETURNTYPE (*func)(), not the __FUNCTOR overload. Here is the code that is failing to compile.
Assert::ExpectException<InvalidArgumentException, int>(&TestClass::TestMethod);
Here is TestMethod:
void TestMethod()
{
}
回答1:
The second type in the ExpectException
template (_RETURNTYPE
in the declaration), needs to match the return type of the function passed into it. You've used int
but your function returns void
, so this gives a compiler error. If you want to be explicit here the second type should be void
. However, as the compiler can figure out the type from the function parameter you don't need to specify it. Try this:
Assert::ExpectException<InvalidArgumentException>(TestClass::TestMethod);
来源:https://stackoverflow.com/questions/18520493/function-pointers-in-c-cx