英文:
Specify function interface in template
问题
我有一个模板类,用于转发函数:
template <class T>
class Foo{
template <typename Func, typename... Args>
void Bar(Func function, Args&&... args) {
T t;
(t->*function)(std::forward<Args>(args)...);
}
}
这个代码是可以工作的,但是有没有办法检查 Func
是否包含在 T
的接口中,即 T::Func
?现在,如果我输入一个错误的函数,编译器会报错说 t->*function
不存在,但是我想在函数接口中指定它应该是一个 T::Func
。然而,我似乎无法找到正确的语法。
英文:
I have a template class that forwards a function:
template <class T>
class Foo{
template <typename Func, typename... Args>
void Bar(Func function, Args&&... args) {
T t;
(t->*function)(std::forward<Args>(args)...);
}
}
This works, but is there any way to check whether Func
is contained in the interface of T
, so T::Func
? Now, if I enter a wrong function the compiler would complain that t->*function
doesn't exist, but I would like to specify in the function interface that it should be a T::Func
. However I can't seem to get the syntax for this right.
答案1
得分: 3
这不是真的必要在签名中指定这一点,因为它无论如何都会在错误的情况下编译失败,但你可以像这样指定成员函数指针:
template <class T>
class Foo{
public:
template <typename Func, typename... Args>
void Bar(Func T::*function, Args&&... args) {
T t;
(t.*function)(std::forward<Args>(args)...);
}
};
调用它的方式如下:
struct S
{
void func(int) {}
};
void freeFunc(int) {}
int main()
{
Foo<S> f;
f.Bar(&S::func, 42); //OK
//f.Bar(&freeFunc, 42); //ERROR
}
英文:
It's not really necessary to specify this in the signature, since it will fail to compile for the wrong cases anyway, but you could specify member function pointers like this:
template <class T>
class Foo{
public:
template <typename Func, typename... Args>
void Bar(Func T::*function, Args&&... args) {
T t;
(t.*function)(std::forward<Args>(args)...);
}
};
And to call it:
struct S
{
void func(int) {}
};
void freeFunc(int) {}
int main()
{
Foo<S> f;
f.Bar(&S::func, 42); //OK
//f.Bar(&freeFunc, 42); //ERROR
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论