繁体   English   中英

模板特化基类函数模板缺失

[英]Template specialization base class function template missing

考虑以下:

#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;
}

编译时,编译器抱怨找不到操作数类型为property<int>int operator=的匹配项。 据我了解,问题是我正在调用不存在的property<int>::operator=(int) 相反,我只定义了property_impl<int>::operator(int)

有没有办法在不需要每个property<T>模板特化来显式实现operator=()的情况下完成这项工作? operator=的实现对于所有专业化都是相同的,所以我正在寻找一种不需要为所有未来的property<T>专业化明确实现的operator=的方法。

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=更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM