草庐IT

c++ - 定义类模板的友元函数模板

coder 2024-02-18 原文

我想定义一个类模板的函数模板。代码如下所示。

template<int M>
struct test{
private:
    int value;

    template<int N = 2 * M>
    friend auto foo(test const t){
        test<N> r;
        r.value = t.value;
        return r;
    }
};

int main(){
    test<1> t;
    foo(t);// expected to return test<2>
    foo<1>(t);// expected to return test<1>
    foo<3>(t);// expected to return test<3>
}

但是它不会编译。与之前的问题相比,下面列出不同之处。

  1. 函数模板的结果涉及类模板的另一个实例化。看来函数模板还得在外面定义。但我不确定。
  2. 函数模板使用默认模板参数。因此,如果函数模板定义在类的外部,则需要辅助函数模板。

使用 g++ -std=c++1z 编译错误:

a.cpp: In instantiation of 'auto foo(test<M>) [with int N = 2; int M = 1]':
a.cpp:16:10:   required from here
a.cpp:4:9: error: 'int test<2>::value' is private
     int value;
         ^
a.cpp:9:17: error: within this context
         r.value = t.value;
                 ^
a.cpp: In instantiation of 'auto foo(test<M>) [with int N = 3; int M = 1]':
a.cpp:18:13:   required from here
a.cpp:4:9: error: 'int test<3>::value' is private
     int value;
         ^
a.cpp:9:17: error: within this context
         r.value = t.value;
                 ^

可能的解决方法,但也不正确。

template<int M>
struct test{
private:
    int value;

    template<int NA, int NR>
    friend test<NR> foo_impl(test<NA> const&);
};

template<int NA, int NR>
test<NR> foo_impl(test<NA> const& t){
    test<NR> r;
    r.value = t.value;
    return r;
}

template<int NR, int NA>
auto foo(test<NA> const& t){
    return foo_impl<NA, NR>;
}

template<int NA>
auto foo(test<NA> const& t){
    return foo_impl<NA, NA * 2>(t);
}

int main(){
    test<1> t;
    foo(t);
    foo<3>(t);
    foo<1>(t);
}

错误:

t.cpp: In function 'int main()':
t.cpp:31:13: error: call of overloaded 'foo(test<1>&)' is ambiguous
     foo<1>(t);
             ^
t.cpp:18:6: note: candidate: auto foo(const test<NR>&) [with int NR = 1; int NA = 1]
 auto foo(test<NA> const& t){
      ^
t.cpp:23:6: note: candidate: auto foo(const test<NA>&) [with int NA = 1]
 auto foo(test<NA> const& t){
      ^

最佳答案

编辑后,一种可能的方法(可能不会比您的解决方法更好 - 但适用于所有调用)是为参数 N 使用默认值:

template<int M>
struct test{
private:
    int value;

    template<int K, int U, int P>
    friend test<P> foo(test<U> const t);

};

template <int N = 0, int M, int P = ((N == 0) ? M * 2 : N)>
test<P> foo (test<M> const t) {
  test<P> r;
  r.value = t.value;
  return r;
}

int main(){
    test<1> t;
    test<2> p1 = foo(t);
    test<3> p2 = foo<3>(t);
    test<1> p3 = foo<1>(t);
}

这可能不会比你的版本更漂亮......


这里的问题是你要声明 foo<N> test<M>的 friend 当你想让它成为任何 test<...> 的 friend 时.您应该执行以下操作:

template<int M>
struct test{
private:
    int value;

    template<int U, int K>
    friend test<K> foo(test<U> const t);
};

template <int M, int N = 2 * M>
test<N> foo (test<M> const t) {
    test<N> r;
    r.value = t.value;
    return r;
}

int main(){
    test<1> t;
    foo(t);
}

这里你是说:

Any function test<K> foo<U, K> (test<U> const) is a friend of any test<...>.

关于c++ - 定义类模板的友元函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37882049/

有关c++ - 定义类模板的友元函数模板的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

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

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

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

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

  5. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  6. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  7. 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

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

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

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

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

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

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

随机推荐