草庐IT

c++ - Typedef、模板和 const 关键字

coder 2024-02-18 原文

我在使用带有 const 关键字(用于函数参数类型)的模板时遇到问题,为了说明这一点,我创建了一个小代码:

template <typename ClassType, typename ReturnType, typename ... Args>
struct MethodCallerFactory
{
    typedef ReturnType (*Type)(ClassType*, Args...);

    template <ReturnType (ClassType::*Pointer)(Args...)>
    struct Method
    {
        static Type createMethodCaller()
        {
            ReturnType (*caller)(ClassType*, Args...) = [](ClassType* obj, Args ... args) -> ReturnType
            {
                 ReturnType (ClassType::*ptr)(Args...) = Pointer;
                                return (obj->*ptr)(args...);
            };
            return caller;
        }
   };
};


class Test
{
public :
        void set(const int& p)
        {
                n = p;
        }
        void set2(int p)
        {
                n = p;
        }
        void set3(const int p)
        {
                n = p;
        }
        void set4(int& p)
        {
                n = p;
        }
private :
        int n;
};

typedef int& INTREF;
typedef int INTVALUE;

int main()
{
        void (*ptr1)(Test*, const int&) = MethodCallerFactory<Test, void, const int&>::Method<&Test::set>::createMethodCaller();
        void (*ptr2)(Test*, const INTREF) = MethodCallerFactory<Test, void, const INTREF>::Method<&Test::set>::createMethodCaller();

        void (*ptr3)(Test*, int) = MethodCallerFactory<Test, void, int>::Method<&Test::set2>::createMethodCaller();
        void (*ptr4)(Test*, INTVALUE) = MethodCallerFactory<Test, void, INTVALUE>::Method<&Test::set2>::createMethodCaller();

        void (*ptr5)(Test*, int) = MethodCallerFactory<Test, void, const int>::Method<&Test::set3>::createMethodCaller();
        void (*ptr6)(Test*, const INTVALUE) = MethodCallerFactory<Test, void, const INTVALUE>::Method<&Test::set3>::createMethodCaller();

        void (*ptr7)(Test*, int&) = MethodCallerFactory<Test, void, int&>::Method<&Test::set4>::createMethodCaller();
        void (*ptr8)(Test*, INTREF) = MethodCallerFactory<Test, void, INTREF>::Method<&Test::set4>::createMethodCaller();
}

我得到的唯一错误是在第二个指针声明上:

could not convert template argument ‘&Test::set’ to ‘void (Test::*)(int&)’ void (ptr2)(Test, const INTREF) = MethodCallerFactory::Method<&Test::set>::createMethodCaller();

似乎当我对引用类型使用 typedef 时,编译器忘记了 const 关键字。我不明白为什么会有问题。

最佳答案

我想纯文本替换让您误以为 const INTREF 会解析为 const int&(等同于 int const&),但是替换实际上解析为 int& const,其中 const 最终被忽略(这是唯一的情况,因为涉及 typedef,因为你不能显式声明 int& const 类型的变量)。所以你最终得到的是 int& 而不是 int const&

在代码中:

#include <type_traits>

typedef int& INTREF;

int main()
{
    static_assert(std::is_same<const INTREF, int&>{}, "!");
}

Live example

这就是为什么有些人(包括我)更喜欢采用 const-after 样式而不是 const-before 样式的原因之一(这两种样式在技术上是等价的): 除了更加一致,1 它允许通过执行直接的文本替换来理解编译器正在做什么。如果您编写的是 INTREF const 而不是 const INTREF,您可能会得出正确的结论。


1 您不能总是将 const 限定符放在它限定的类型之前,但您总是可以将它放在后面。例如,您可以将类型“指向常量整数的常量指针”拼写为 int const* const(其中 const 关键字始终应用于它之前的所有内容) , 但语法不允许这样写 const const int*; const int* const 是允许的,但它混合了 const-before 和 const-after,从而降低了一致性。

关于c++ - Typedef、模板和 const 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30545972/

有关c++ - Typedef、模板和 const 关键字的更多相关文章

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

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

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

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

  3. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  4. ruby-on-rails - Mandrill API 模板 - 2

    我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h

  5. ruby - Chef Ruby 遍历 .erb 模板文件中的属性 - 2

    所以这可能有点令人困惑,但请耐心等待。简而言之,我想遍历具有特定键值的所有属性,然后如果值不为空,则将它们插入到模板中。这是我的代码:属性:#===DefaultfileConfigurations#default['elasticsearch']['default']['ES_USER']=''default['elasticsearch']['default']['ES_GROUP']=''default['elasticsearch']['default']['ES_HEAP_SIZE']=''default['elasticsearch']['default']['MAX_OP

  6. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  7. ruby - Ruby 的 AST 中的 'send' 关键字是什么意思? - 2

    我正在尝试学习Ruby词法分析器和解析器(whitequarkparser)以了解更多有关从Ruby脚本进一步生成机器代码的过程。在解析以下Ruby代码字符串时。defadd(a,b)returna+bendputsadd1,2它导致以下S表达式符号。s(:begin,s(:def,:add,s(:args,s(:arg,:a),s(:arg,:b)),s(:return,s(:send,s(:lvar,:a),:+,s(:lvar,:b)))),s(:send,nil,:puts,s(:send,nil,:add,s(:int,1),s(:int,3))))任何人都可以向我解释生成的

  8. arrays - Ruby 数组 += vs 推送 - 2

    我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“

  9. ruby-on-rails - `const_missing' : uninitialized constant (NameError) - 2

    每次我尝试使用“script/runner-eproductionClassName.run”从我的Rails2.2应用程序的lib目录运行任何类时,我都会收到以下错误:/usr/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/commands/runner.rb:47:/usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:89:in`const_missing':uninitializedconstantClassName(NameError)

  10. += 的 Ruby 方法 - 2

    有没有办法让Ruby能够做这样的事情?classPlane@moved=0@x=0defx+=(v)#thisiserror@x+=v@moved+=1enddefto_s"moved#{@moved}times,currentxis#{@x}"endendplane=Plane.newplane.x+=5plane.x+=10putsplane.to_s#moved2times,currentxis15 最佳答案 您不能在Ruby中覆盖复合赋值运算符。任务在内部处理。您应该覆盖+,而不是+=。plane.a+=b与plane.a=

随机推荐