让我们考虑一种“调用”函数(这里称为“调用”),它有助于调用由模板参数传递的成员函数。在这个函数中,我需要知道拥有成员函数的类的类型。有没有办法(最好在 c++14 中)这样做?
#include <functional>
template<typename F, typename... Args, std::enable_if_t<std::is_member_pointer<std::decay_t<F>>{}, int> = 0 >
constexpr decltype(auto) call(F&& f, Args&&... args) noexcept(noexcept(std::mem_fn(f)(std::forward<Args>(args)...)))
{
// Here we know that f is a member function, so it is of form : &some_class::some_function
// Is there a way here to infer the type some_class from f ? For exemple to instantiate a variable from it :
// imaginary c++ : class_of(f) var;
return std::mem_fn(f)(std::forward<Args>(args)...);
}
int main()
{
struct Foo { void bar() {} …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用constexpr和static_assert.我实际上需要检查constexpr字符串的长度,该字符串由专用函数计算.这是我正在尝试运行的:
#include <iostream>
using namespace std;
class Test
{
private :
static constexpr char str[] = "abc";
static int constexpr constStrLength(const char* str)
{
return *str ? 1+constStrLength(str+1) : 0;
}
static constexpr int length = constStrLength(str);
static_assert(length ==3, "error");
public :
static void f()
{
cout << len << endl;
}
};
int main()
{
Test::f();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
错误:'static constexpr int Test :: constStrLength(const char*)'在常量表达式中调用static constexpr int len = constStrLength("length");
什么是实现它的正确方法?
感谢帮助 !