本文介绍了构造函数中的模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个''Command''类,其构造函数接受一个

模板参数T的实例。然后构造函数打印出
$ b $的名称b传递给它的T类。当我提前构建T类实例化Command时,它可以工作。当我在*

命令构造函数中构造T类*时,它不起作用。任何想法?


================代码如下===============


#include< iostream>


class命令

{

public:


模板< class T>显性命令(T& t)

{

std :: cout<< typeid(T).name()<< std :: endl;

}

};


class Bar {};


int main()

{

Bar b;

命令cmd(b); //这有效

命令cmd2(Bar()); //这不是


返回0;

}

I''ve got a ''Command'' class whose constructor takes an instance of a
template argument T. The constructor then prints out the name of the
class T that was passed to it. When I construct the T class in advance
of instantiating Command, it works. When I construct the T class *in*
the Command constructor, it doesn''t work. Any ideas?

================ CODE FOLLOWS ===============

#include <iostream>

class Command
{
public:

template<class T> explicit Command(T & t)
{
std::cout << typeid(T).name() << std::endl;
}
};

class Bar { };

int main()
{
Bar b;
Command cmd(b); // This works
Command cmd2(Bar()); // This doesn''t

return 0;
}

推荐答案




V



V






在这不会中你创建一个临时对象的情况。暂时的

对象是一个r值。 R值不能绑定到对

非const的引用。要修复错误,你的模板化构造函数接受

T by value(T t)或引用const(T const& t)。

-

Maxim Yegorushkin



In the "This doesn''t" case you create a temporary object. A temporary
object is an r-value. R-value can not be bound to a reference to a
non-const. To fix the error make your templated constructor accept either
T by value (T t) or by reference to const (T const& t).
--
Maxim Yegorushkin


这篇关于构造函数中的模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:22
查看更多