草庐IT

c++ - 处理类和类的模板函数*

coder 2024-02-20 原文

下面的代码允许我模板化一个函数 接受一个参数,该参数是指向 Box 对象的三种不同指针类型之一的 vector :

const std::vector<std::shared_ptr<Box>>&
const std::vector<std::weak_ptr<Box>>&
const std::vector<Box*>&

有没有办法扩展它以支持:

const vector<Box>& 
const vector<std::reference_wrapper<Box>>

也许有一些 boost ?

#include <vector>
#include <iostream>

class Box{
public:

    Box (unsigned int id, unsigned int side): id(id), side(side){}

    int volume(){
        return side * side * side;
    }
    unsigned int id;
    unsigned int side;

};

template <typename T>
struct is_box_containter {
    enum { value = false };
};

template <>
struct is_box_containter <std::vector<std::shared_ptr<Box>>> {
    enum { value = true };
};

template <>
struct is_box_containter <std::vector<std::weak_ptr<Box>>> {
    enum { value = true };
};

template <>
struct is_box_containter <std::vector<Box*>> {
    enum { value = true };
};

template <typename T>
typename std::enable_if<is_box_containter<T>::value>::type
measure(T const& boxes )
{
    for (auto& box : boxes) {
        std::cout << box->id << " has volume " << box->volume() << std::endl;
    }
}

int main (){

    std::vector<std::shared_ptr<Box>>  some_boxes;
    some_boxes.push_back(std::shared_ptr<Box>(new Box(1,4)));
    some_boxes.emplace_back(new Box(2, 12));
    Box * box_3 = new Box(3, 8);
    Box * box_4 = new Box(4, 9);

    std::vector<Box*>  more_boxes;
    more_boxes.emplace_back(box_3);
    more_boxes.emplace_back(box_4);

    measure(some_boxes);
    measure(more_boxes);

    return 0;
}

为什么我要问这个问题: 我有一个具有两个功能的应用程序,它们实现了几乎相同的逻辑。一个接受 SomeClass 的列表,另一个接受指向 SomeClass 的指针 vector 。 我目前正计划重构代码以将 SomeClass 列表替换为指向 SomeClass 的共享指针列表。但我这样做的唯一原因是将逻辑转移到一个通用的实现中。如果有一种完全合理的方法可以避免它,我不想这样做。

最佳答案

如果我正确理解你的问题,你可以使用如下的解引用机制:

template<typename T> 
T& dereference(T &v) {
  return v;
}

template<typename T> 
const T& dereference(const T& v) {
  return v;
}

template<typename T> 
typename std::enable_if<!std::is_function<T>::value, T&>::type dereference(T* v) {
  return dereference(*v);
}

template<typename T> 
const T& dereference(const std::shared_ptr<T>& v) {
  return dereference(*v);
}

template<typename T> 
const T& dereference(const std::weak_ptr<T>& v) {
  return dereference(*v);
}

template<typename T> 
const T& dereference(const std::reference_wrapper<T>& v) {
  return v;
}

然后像这样调用你的数据:

template <typename T>
typename std::enable_if<is_box_containter<T>::value>::type
measure(T const& boxes )
{
    for (auto& box : boxes) {
        std::cout << dereference(box).id 
                  << " has volume " << dereference(box).volume() << std::endl;
    }
}

LIVE DEMO

P.S 你还必须定义:

template <>
struct is_box_containter <std::vector<Box>> {
    enum { value = true };
};

template <>
struct is_box_containter <std::vector<std::reference_wrapper<Box>>> {
    enum { value = true };
};

关于c++ - 处理类和类的模板函数*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32991091/

有关c++ - 处理类和类的模板函数*的更多相关文章

  1. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  4. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  5. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  6. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  7. Ruby——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

  8. ruby-on-rails - 使用 config.threadsafe 时从 lib/加载模块/类的正确方法是什么!选项? - 2

    我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co

  9. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  10. 没有类的 Ruby 方法? - 2

    大家好!我想知道Ruby中未使用语法ClassName.method_name调用的方法是如何工作的。我头脑中的一些是puts、print、gets、chomp。可以在不使用点运算符的情况下调用这些方法。为什么是这样?他们来自哪里?我怎样才能看到这些方法的完整列表? 最佳答案 Kernel中的所有方法都可用于Object类的所有对象或从Object派生的任何类。您可以使用Kernel.instance_methods列出它们。 关于没有类的Ruby方法?,我们在StackOverflow

随机推荐