草庐IT

C++ 多参数模板化类成员特化

coder 2024-02-19 原文

我正在设置一个 c++(11) 程序,我在其中使用了一个依赖于 2 个参数的模板化类。该类的大部分内容都可以根据模板参数进行通用编写。只有少数功能需要专门的版本。这是重现我的问题的示例模式:

template<class T, int N> 
class foo
{
  // typedefs and members that depend on T and N
  // but that can be written generically e.g. :
  typedef std::array<T,N> myarray;
  void myfunc(myarray tab);
};

// ...

template<class T, int N>
foo<T,N>::myfunc(myarray tab)
{
  // generic version
}

// need specialization only of myfunc:
template<class T>
foo<T,1>::myfunc(myarray tab)
{
  // specialized version for N=1
}

然后编译器报错:error: invalid use of incomplete type ‘class foo<T, 1>’关于然后行 template<class T> foo<T,1>::myfunc(myarray tab)

我发现唯一可行的解​​决方法是插入一个完整的类及其专用版本的拷贝:

template<class T>
class foo<T,1>
{
  // recopy all the lines of class foo<T,N>, replacing N by 1
};
// duplicate as well all generic function definition with 
// specialized versions <T,1> even when not needed

什么是很不满意...

经过一些实验,我发现当模板只使用 1 个参数时(例如 template <int N> class foo{...}; )似乎不会出现此问题,但只有涉及至少 2 个参数时才会出现此问题。

这是 C++ 编程中众所周知的东西吗?有没有更聪明的方法来解决我的问题? (我想创建一个没有专门功能的母类,然后让类 foo 继承它,只保留专门的成员,以尽量减少“重复解决方法”)

多谢指教!

最佳答案

标签 dispatch 救援。

使用 std::integral_constant,我们可以创建两种类型,一种用于通用 N,另一种用于 1(或者您可以在 int 上定义一些其他类型模板,但我选择使用已经存在的东西)。

void myfunc(myarray tab)
{
    myfunchelper(tab, 
       typename std::is_same<std::integral_constant<int, N>,
                             std::integral_constant<int, 1>>::type{});
}

它将调用分派(dispatch)到为 std::true_type(N==1 的场景)和 std::false_type 重载的辅助函数>(N != 1 的场景):

void myfunchelper(myarray tab, std::false_type);
void myfunchelper(myarray tab, std::true_type);

请注意,我故意不命名该类型,因为它未被使用,并且智能编译器会优化掉该类型的任何类型的分配(我认为)。

Live Demo

(来自下面演示的代码):

#include <array>
#include <iostream>
#include <type_traits>

template<class T, int N> 
class foo
{
public:
  // typedefs and members that depend on T and N
  // but that can be written generically e.g. :
  typedef std::array<T,N> myarray;
  void myfunc(myarray tab)
  {
      myfunchelper(tab, typename std::is_same<std::integral_constant<int, N>, std::integral_constant<int, 1>>::type{});
  }
  
private:
  void myfunchelper(myarray tab, std::false_type)
  {
      std::cout << "Generic myfunc\n";
  }
  void myfunchelper(myarray tab, std::true_type)
  {
      std::cout << "myfunc specialized for N==1\n";
  }
};

int main()
{
    std::array<char, 1> arr1{{'c'}};
    std::array<double, 2> arr2{{1.0, 2.0}};
    foo<char, 1> f1;
    foo<double, 2> f2;
    f1.myfunc(arr1); // calls specialized version
    f2.myfunc(arr2); // calls generic version
}

关于您发布的解决方案,这也是一种标记调度方法,它涉及定义另一个 int-template 类,该类将不必要的类型引入周围范围,并且还涉及强制转换a 和 NULL(好吧,在这种情况下为 0,这就是 NULL 通常的类型定义)。

实际上,我发布的解决方案是相同的,但我认为它更清晰一些,类型更安全一些。

关于C++ 多参数模板化类成员特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36503428/

有关C++ 多参数模板化类成员特化的更多相关文章

  1. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  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 - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  5. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  6. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  7. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  8. ruby-on-rails - Rails 模型——非持久类成员或属性? - 2

    对于Rails模型,是否可以/建议让一个类的成员不持久保存到数据库中?我想将用户最后选择的类型存储在session变量中。由于我无法从我的模型中设置session变量,我想将值存储在一个“虚拟”类成员中,该成员只是将值传递回Controller。你能有这样的类(class)成员吗? 最佳答案 将非持久属性添加到Rails模型就像任何其他Ruby类一样:classUser扩展解释:在Ruby中,所有实例变量都是私有(private)的,不需要在赋值前定义。attr_accessor创建一个setter和getter方法:classUs

  9. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  10. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

随机推荐