检查模板类是否存在函数
Check template class for existence of function
我想在编译时检查提供的模板类是否存在某些方法。编造的示例代码:
template <class AudioSystem>
class Car {
public:
Car() {/*nothing related to AudioSystem*/}
void getsCalledLater(AudioSystem* a) {/*...*/}
void Verify() {
// check if class AudioSystem has function double hasFeature(int, double)
// check if class AudioSystem has function double getCreationDate()
}
~Car() {
Verify();
}
};
调用构造函数时我没有AudioSystem
对象,所以我不能只对方法进行测试调用。另外:我不能假设音频系统的默认 ctor 可用。
我已经在SO上发现了这个问题,它指出了
http://www.gotw.ca/gotw/071.htm
但我不明白这个无辜的单行解决方案:
// in Validation method:
T* (T::*test)() const = T::Clone; // checks for existence of T* T::Clone() const
任何帮助,不胜感激。
(如果在无法访问默认 ctor 的情况下无法实现,我也许可以放弃该要求。
行
T* (T::*test)() const = T::Clone;
声明test
为指向T
的常量成员函数的指针,后者不带任何参数并返回指向T
的指针。然后它初始化以指向T::Clone
成员函数。现在,如果T::Clone
的签名与(void)->T*
签名不同或不存在,则会收到错误。
非常聪明。
让我们看这个例子:
template<typename T>
class Check // checks for the existence of `T* T::Clone() const`
{
public:
~Check()
{
T* (T::*test)() const = &T::Clone;
// test; // don't think you need this line
}
};
class Foo
{
public:
Foo* Clone() const{}; // try changing the signature, remove `const` for example
};
int main()
{
Check<Foo> testFoo; // ok
}
现在尝试从 Foo::Clone()
的签名中删除const
,或使其返回 int
,您将获得编译时错误,因为 Check<T>
中声明的指针不再与正确类型的函数兼容。希望这是有道理的。
请注意,这种验证是在编译时完成的,因此您不能使用返回true
或false
的bool
函数(就像您现在尝试执行的那样),因为这意味着运行时决策。所以你必须使用这种技巧,如果函数存在,那么程序将编译,如果没有,你会得到一个编译时错误。
因此,在您的情况下,例如要测试是否存在double AudioSystem::hasFeature(int, double)
,您需要声明
double (AudioSystem::*test)(int, double) = AudioSystem::hasFeature;
相关文章:
- C++模板来检查友元函数的存在
- C++quit()函数中可能存在作用域问题
- g++ 说函数不存在,即使包含正确的标头
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 根据某个函数是否存在启用模板
- 尝试根据类中 typedef 的存在来专门化模板函数
- 无论如何,我可以确定构造函数是否存在吗?
- 当覆盖存在时调用基本虚拟"binded to object"函数
- 扩展类中的可选 vir 函数,测试它在运行时是否存在
- C++ 中的函数 GetCursorPos() 和 SetCursorPos() 存在一些问题
- C++ 用于检查容器类中是否存在函数和隐式推导规则的概念
- 当模板重载可用时,检查是否存在函数的自定义重载
- C++'Undefined reference to'错误,尽管包含路径中的头文件中存在函数定义
- 如何使用CPPCHECK查找CPP文件中是否存在函数
- 检查 Linux 库中是否存在函数
- 检查模板类是否存在函数
- 存在函数模板时的参数转换
- 如何检查 C/C++ 中是否存在函数
- 未定义的引用错误,即使存在函数