c++ - 显式使用模板,C++

标签 c++ templates explicit

我有一个关于显式和模板的问题:

template<class T> 
class A {

    class A_Impl {
        T var;

        public:
            explicit A_Impl(T var1) : var(var1), version(1) 
            {
            }

            A_Impl(const A_Impl& a ) : var(a.var), version(1) 
            {
            }

            const A_Impl& operator=(const A_Impl& a)
            {
                var=a.var;++version;return *this;   
            }

            operator T() const { return var; }

            friend class A<T>;
    };

    A_Impl a;

public:
    A(T var): a(var) 
    {
    }

    A_Impl& get() { return a; }
};

void main() {
    A<int> a1(5);
    cout<<"a1 = "<<a1.get()<<endl;

    a1.get()=7;
    cout<<"a1 = "<<a1.get()<<endl;

    a1=13;
    cout<<"a1 = "<<a1.get()<<endl;
}

我在 a1.get()=7; 处遇到错误,表示没有运算符“=”匹配这些操作数

此外,如果我明确指出它会编译,但我不明白 a1.get() 函数和 a1=13; 之间的区别即使有显式也很好。

最佳答案

I get en error at a1.get()=7; which says no operator "=" matches these operands

对于 operator=,无法将 7 转换为 A_Impl,因为构造函数 A_Impl(T),在此实例中扩展为 A_Impl(int),声明为 explicit

您可以删除 explicit 关键字,或者显式创建一个 A_Impl :

a1.get() = A_Impl(7); 

或者你也可以声明一个特定的operator=:

const A_Impl& operator=(const T&)

对于 A_Impl 类。


Also, if i take explicit word out it will compile, but i dont understand the difference between the a1.get() function and a1=13; which works fine even with explicit.

a1 = 13 工作正常,因为模板类 A 有一个 非显式 构造函数到 T (特别是 A(T var)),在这种情况下,它与 T = int 完美匹配。


另请注意,main 应始终返回 int,而不是 void

关于c++ - 显式使用模板,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21204277/

相关文章:

C++ 如何在不尝试 {} finally{} 的情况下安全地关闭文件?

C++ - 相互对象包含

java - 隐式 super 构造函数。必须显式调用另一个构造函数

c++ - 为什么显式模板实例化的位置很重要

C++ cUrl 将多部分/表单数据文件发送到 Web 服务器

c++ - C++ 中的命令处理器与控制台

c++ - 用户定义的转换运算符优先级,在 g++ 中编译但在 clang++ 中不编译

c++ - 选择模板参数包中的每个偶数(或奇数)参数

c++ - 非常基本的模板功能出现问题

c++ - 模板生成器错误的显式复制构造函数