【问题标题】:Is there a way to check if a function (name and signature) has been define within a namespace有没有办法检查一个函数(名称和签名)是​​否已在命名空间中定义
【发布时间】:2015-07-22 02:45:16
【问题描述】:

我想在模板方法中调用命名空间定义的函数,并且想使用 std::enable_if 让该方法仅在目标命名空间定义的函数存在时生成。有可能吗?

我应该补充一点,调用方法需要一个参数,该参数的类型在命名空间中定义。这就是我要检查的命名空间。

namespace SomeNamespace
{
    ...
    void SomeFunc(...);

    class SomeType { ... };
}

template <class T>
void MyClass::MyMethod(const SomeNamespace::SomeType& obj)
{
   ...
   SomeNamespace::SomeFunc(...);
   ...
}

【问题讨论】:

  • 除非SomeFunc 有一个在某种程度上与SomeType 相关的参数。
  • 你能澄清一下吗?当你对@toth 说目标命名空间是任意的 时,你是说你甚至不知道它的名字,还是你只是说它是一个命名空间是给定的吗?
  • @Mike Kinghan:在上面的帖子中,“我应该添加...”下面的代码具有 SomeNamespace,这就是我的意思。

标签: c++11


【解决方案1】:

不确定您是否可以使用std::enable_if 做到这一点,但实现它的一种方法如下(假设func 采用单个参数,应该很容易推广到多个参数):

#include <iostream>

namespace NS {
   void func(int x)
   {
      std::cout << "func called with arg " << x << std::endl;
   }


   void call_func(...)
   {
      std::cout << "func does not exist" << std::endl;
   }

   template<typename T>
   auto call_func(T t) -> decltype( func(t), void())
   {
      std::cout << "func exists, calling it" << std::endl;
      func(t);
   }
} 

int main()
{
    call_func(2);
    return 0;
}

这将产生输出

func exists, calling it
func called with arg 2

但是如果你注释掉func的定义,你会得到:

func does not exist

这有点笨拙,因为call_func 重载需要定义在与func 相同的命名空间内,否则它不起作用。为了使其更可重用,您可以使用 NSfunc args 将 call_func 定义包装在某个宏中。

【讨论】:

  • 感谢您的建议。但我追求的是一个可以处理任意命名空间的解决方案。不幸的是,在我的环境中使用宏不是一个选项。
  • @simon,我认为那是不可能的。该语言无法使用命名空间的名称作为参数(模板或其他),但宏除外。
猜你喜欢
  • 2011-04-01
  • 2013-11-04
  • 2019-06-11
  • 1970-01-01
  • 2010-11-21
  • 2014-10-18
  • 2012-10-30
  • 1970-01-01
相关资源
最近更新 更多