【问题标题】:Preprocessor conditions in a template模板中的预处理器条件
【发布时间】:2014-06-12 11:31:14
【问题描述】:

我目前正在为函数创建模板,如果模板在特定类中,我需要一种方法,使函数中没有代码,我已经尝试过下面的内容,但我没想到它会起作用,它是 C++,太方便了 :P 其他人对我如何实现这一点有任何建议吗?

template<typename T> int Position::lSetPosition(lua_State* L){
    #if T != Pro::Scene::Scene
        auto p = Util::luaP_touserdata<T>(L, 1);
        auto v = Math::Vector2(static_cast<int>(lua_tonumber(L, 2)),
            static_cast<int>(lua_tonumber(L, 3)));
        p->setPosition(v);
        return 0;
    #endif 
}

【问题讨论】:

  • 你为什么不专门为 Pro::Scene::Scene 做任何事情的模板?

标签: c++ templates c-preprocessor


【解决方案1】:

这是使用模板专业化的好地方。尝试以下方法:

template<typename T> int Position::lSetPosition(lua_State* L) {
  auto p = Util::luaP_touserdata<T>(L, 1);
  auto v = Math::Vector2(static_cast<int>(lua_tonumber(L, 2)),
      static_cast<int>(lua_tonumber(L, 3)));
  p->setPosition(v);
  return 0;
}

template<> int Position::lSetPosition<Pro::Scene::Scene>(lua_State* L) {}

从本质上讲,模板专业化允许您根据模板类或函数的类型来实现不同的实现,这正是您想要的。对T 类型做一些事情,对Pro::Scene::Scene 类型做一些别的事情。当编译器看到您在模板中指定的类型时,它会自动选择正确的类型来使用。

【讨论】:

  • 很好的解决方案 - 或许可以稍微解释一下它的工作原理和原因?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 2016-06-30
  • 2010-11-11
  • 1970-01-01
  • 2012-04-14
  • 2012-08-14
  • 1970-01-01
相关资源
最近更新 更多