c++ - 模板特化基类函数模板缺失

标签 c++ templates

考虑以下:

#include <iostream>
#include <string>

/**
 * Provides base functionality for any property.
 */
struct property_base
{
    virtual std::string to_string() const = 0;
    
protected:
    void notify() { std::cout << "notifying!" << std::endl; }    
};

/**
 * Generic property implementation template.
 */
template<typename T>
struct property_impl :
    property_base
{
    T data;
    
    property_impl<T>& operator=(const T& t)
    {
        this->data = t;
        this->notify();
        return *this;
    }
};

/**
 * Generic property template.
 */
template<typename T>
struct property :
    property_impl<T>
{
};

/**
 * 'int' property specialization
 */
template<>
struct property<int> :
    property_impl<int>
{
    std::string to_string() const { return std::to_string(data); }
};

/**
 * `std::string` property specialization
 */
template<>
struct property<std::string> :
    property_impl<std::string>
{
    std::string to_string() const { return data; }  
};

int main()
{
    property<int> x;
    property<std::string> str;
    
    x = 42;
    str = "Hello World!";
    
    return 0;
}
编译时,编译器提示找不到 operator= 的匹配项。操作数类型 property<int>int .据我了解,问题是我正在调用 property<int>::operator=(int)这不存在。相反,我只有 property_impl<int>::operator(int)定义。
有没有一种方法可以在不需要每个 property<T> 的情况下完成这项工作?模板特化显式实现 operator=() ? operator=的执行对于所有特化都是相同的,所以我正在寻找一种不需要显式实现 operator= 的方法为所有 future property<T>专业。
Coliru 链接到思想家:http://coliru.stacked-crooked.com/a/1db9165e4f78ffa4

最佳答案

C++ 中很少有事情是自动发生的。幸运的是,在这种情况下您不必编写很多额外的代码,只需添加一个 using对每个子类的声明:

/**
 * 'int' property specialization
 */
template<>
struct property<int> :
    property_impl<int>
{
    using property_impl<int>::operator=;
    std::string to_string() const { return std::to_string(data); }
};

/**
 * `std::string` property specialization
 */
template<>
struct property<std::string> :
    property_impl<std::string>
{
    using property_impl<std::string>::operator=;
    std::string to_string() const { return data; }
};
您必须明确添加 using声明到这个子类,但这仍然比复制/粘贴相同的 operator= 更好在他们每个人中。

关于c++ - 模板特化基类函数模板缺失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64912800/

相关文章:

python - QFileSystemWatcher 不为另一个应用程序所做的更改发出 fileChanged 信号

c++ - N维 vector 的递归可变参数模板函数

c++ - C++ 模板的替代方案

c++ - 模板和#defines 的奇怪行为

c++ - Visual Studio 2013 - C++ 错误

c++ - 如果一个类继承 NSObject 会有多少开销

c++ - C++ 中带有 self 的复合赋值运算符

python - Django 模板 : False vs. 无

c++ - 仅更改一个成员函数的类模板特化

c++ - 函数指针和类模板