英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论