C++ 检查模板类是否存在函数

C++ 检查模板类是否存在函数,c++,templates,C++,Templates,我想在编译时检查提供的模板类是否存在一些方法。组成示例代码: template <class AudioSystem> class Car { public: Car() {/*nothing related to AudioSystem*/} void getsCalledLater(AudioSystem* a) {/*...*/} void Verify() { // check if class AudioSystem has function do

我想在编译时检查提供的模板类是否存在一些方法。组成示例代码:

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();
  }
};
感谢您的帮助

(如果无法访问默认的ctor,我可能可以放弃该要求。)

T* (T::*test)() const = T::Clone;
test
声明为指向
T
的const成员函数的指针,后者不接受任何参数并返回指向
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
}

您只是想确保成员函数存在,还是想根据该函数是否存在来切换模板专门化?这也可以在编译时完成。@KerrekSB:只需确保(即,如果不存在则停止编译),但另一种情况也会很有趣@mstrkrft:对于一般情况,有众所周知的SFINAE技术。可能不值得在这里重复,在这个网站上应该有几个关于这个的帖子。谢谢!对于我的示例,函数
double test(int,double)
,解决方案是
double(T::*test)(int,double)=&T::test
。是的,忘记发布问题的解决方案:)将更新答案,使其看起来如此。在这种情况下,是否有机会向编译器输出添加消息(如通过static_assert)?@mstrkrft这是一个好问题,可能一些元模板专家可以提出解决方案,但现在我不知道如何做。你可以看看这里,
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
}
double (AudioSystem::*test)(int, double) = AudioSystem::hasFeature;