Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
模板类中引用的类型检查是否不那么严格? 以下是通过升级的C++中的允许: int ivalue = true; bool bvalue = 1;_C++_Templates_Types_Reference - Fatal编程技术网

模板类中引用的类型检查是否不那么严格? 以下是通过升级的C++中的允许: int ivalue = true; bool bvalue = 1;

模板类中引用的类型检查是否不那么严格? 以下是通过升级的C++中的允许: int ivalue = true; bool bvalue = 1;,c++,templates,types,reference,C++,Templates,Types,Reference,没关系。通过类型检查,这是不允许的: int& ivalue = false; bool& bvalue = 0; 没关系 看看这个,来自维基百科。 #包括 模板类属性{ T值; 公众: T和运算符=(常数T和i){ ::std::cout否,无论是否涉及模板,类型转换和引用绑定规则都是相同的。您可以将临时(例如当仲裁人与引用的类型不同时所需的临时)绑定到常量引用,但不能绑定到非常量引用 这就是第二对示例未能编译的原因,也是在较大的示例中,当参数类型与模板参数不匹配时,模板运

没关系。通过类型检查,这是不允许的:

int& ivalue = false;
bool& bvalue = 0;
没关系

看看这个,来自维基百科。

#包括
模板类属性{
T值;
公众:
T和运算符=(常数T和i){

::std::cout否,无论是否涉及模板,类型转换和引用绑定规则都是相同的。您可以将临时(例如当仲裁人与引用的类型不同时所需的临时)绑定到
常量
引用,但不能绑定到非
常量
引用


这就是第二对示例未能编译的原因,也是在较大的示例中,当参数类型与模板参数不匹配时,模板
运算符=
未能编译的原因。在这两种情况下,代码都会尝试通过类型转换创建临时,并将其绑定到非
常量
引用。

ace是误导性的。
int&i=5;
同样是不允许的。与类型提升无关。@Kerrek SB:我现在完全迷路了……他不是说第二块代码是不允许的吗?@K-ballo:OP暗示错误与类型有关,但事实并非如此(你知道,这与右值有关).也许我喝了太多啤酒(TGIF),但问题到底是什么?
#include <iostream>

template <typename T> class property {
        T value;
    public:
        T & operator = (const T &i) {
            ::std::cout << "T1: " << i << ::std::endl;
            return value = i;
        }
        // This template class member function template serves the purpose to make
        // typing more strict. Assignment to this is only possible with exact identical
        // types.
        template <typename T2> T2  operator = (const T2 &i) {
            ::std::cout << "T2: " << i << ::std::endl;
            T2 &guard = value;
        return value = i;
            throw guard; // Never reached.
        }/**/
        operator T const & () const {
            return value;
        }
};

struct Bar {
    // Using the property<>-template.
    property <bool> alpha;
    property <unsigned int> bravo;
};

int main () {
    Bar bar;
    bar.alpha = true;
    bar.bravo = true; // This line will yield a compile time error
                      // due to the guard template member function.
    ::std::cout << foo.alpha << ", "
                << foo.bravo << ", "
                << bar.alpha << ", "
                << bar.bravo
                << ::std::endl;


    bool bvar = 22;
    int ivar = true;
    //int &newvar = bvar;

    print(bvar);

    ::std::cout << bvar << " and " << ivar << "\n";
    return 0;
}